Niteesh
Niteesh

Reputation: 121

Android Application that connects to remote server

I am trying to build an Android App on Platform 2.2 Froyo. The app is supposed to connect to a remote server, fetch data from it and display to user in a different language.

Note - I have already installed the Android platform and have built simple apps like Hello, world. I know Java. Also I am using Eclipse.

Thank you for your answers. No rude comment please...

//--------------Code for connecting to web using HTTP protocol-----------------//

package in.androidbook.Networking;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity 
{
    ImageView img;
    /* This is for making asynchronous calls to ensure that connection to server will not return until data is received */

    private class BackgroundTask extends AsyncTask<String, Void, Bitmap>
    {
        protected Bitmap doInBackground(String...url)
        {
            Bitmap bitmap = DownloadImage(url[0]);
            return bitmap;
        }

        protected void onPostExecute(Bitmap bitmap)
        {
            ImageView img = (ImageView) findViewById(R.id.img);
            img.setImageBitmap(bitmap);         
        }
    }
    // Code for making HTTP connection
    private InputStream OpenHttpConnection(String urlString) throws IOException 
    {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);//We take an object of class URL
        URLConnection conn = url.openConnection(); //Create a connection object and open the connection

        if(!(conn instanceof HttpURLConnection)) throw new IOException("Not an Http connection");
        try
        {
            HttpURLConnection httpConn = (HttpURLConnection) conn; //httpConn object is assigned the value of conn. Typecasting is done to avoid conflict.
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();
            response = httpConn.getResponseCode();

            if(response == HttpURLConnection.HTTP_OK)
                in = httpConn.getInputStream();
        }
        catch (Exception ex)
        {
            throw new IOException("Error connecting");
        }
        return in;
    }   
        //------------------------------------------ OpenHttpConnection method completed----------------------------------------------------------//
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------//
    //-------------------------------Method to download an image--------------------------------------------------------------------------------------//
    private Bitmap DownloadImage(String URL)
    {
        Bitmap bitmap = null;
        InputStream in = null;
        try
        {
            in = OpenHttpConnection(URL);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException e1)
        {
            Toast.makeText(this, e1.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            //Toast displays a short msg to user. this refers to current object.
            e1.printStackTrace();
        }
        return bitmap;
    }  


/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       Bitmap bitmap = DownloadImage("http://i.zdnet.com/blogs/3-29-androids.jpg");
        img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(bitmap);
    }
}

Upvotes: 0

Views: 9430

Answers (3)

Martin
Martin

Reputation: 7723

UPDATED (based on comment) : As we are talking about the client side, I confirm my answer. If the site is not yours, the first thing you need to do if check how/if it allows for some kind of communication via API, and in what kind of format (XML and JSON being the most used). With this information, it should be pretty easy. Take a look of the Android example using the Google Map or Twitter, you should find some.

Well, it depends what do you mean exactly : are you asking for the skills needed on the client side (the app) - in the idea that the server is already built, or will be by someone else, or the skills needed for the server ?

In the former case, I would advice to communicate with REST API and JSON. Take a look at apache HTTPGet, HTTPClient and HTTPResponse class and org.json (all are included in Android). If you want to test with them, use some public APIs (so you do not have to worry about the server), such as Google Map API (which is simple and free to use under some limits).

In the latter case, I'm with ColWinters : if you know java, use it there also, with Tomcat as a server and a basic Servlet. You'll find examples aplenty on the Internet.

Upvotes: 2

kosa
kosa

Reputation: 66677

If you know java, I would suggest servlet as service hosted on server which reads data from mysql or anydatabase and contructs as json. in your android app make http using in buit httpclient to remote servlet and parse json response. So. Servlets,Httpclient,Json covers most if your app is native to phone app.

Upvotes: 1

L7ColWinters
L7ColWinters

Reputation: 1362

Look up these technologies,

Apache Tomcat - Java Server Pages (server processing) MySQL (storage of data)

and thats it. Also make sure to do the request in a seperate thread like an Async Task from an activity.

Upvotes: 1

Related Questions