Sunday, April 22, 2012

Set up and Create android application in few hours



I keen to use unorthodox approach. So I have been developing android apps with InteliJ IDE with android SDK from few months back. But lately I realized the best approach is eclipse + Android SDK + ADT development environment, cause of plenty of available support. So today’s my article write along with them.
Android is popular today. So apparently most of the people / systems use simple android versions of their client apps, around http web requests. So awareness of these is worth for any programmer from any background.



Simple steps to setup development environment
Search and download eclipse Indigo (Eclipse for Java EE).
Search and download latest android SDK
Search and download latest ADT plug-in for eclipse Indigo 

Please keep in mind, Download latest versions. Because if you mix up the stuff, like using latest ADT with eclipse Galileo (released in 2009) I’m sure it will destroy your day. And make sure to download eclipse RCP version for java EE.

  1. Install Latest java version ( ex – 1.7 )
  2. Install AndroidSDK. Go to installation folder open SDK manager and install relevant components.
  3. After install SDK ,  set Path variables to tools and platform-tools folders.
  4. Exact eclipse package to separate folder. Open up eclipse by double clicking exe.
  5. Navigate help – Install New Software - Add ADT by locating a path.
  6. Restart eclipse.
  7. Ok then you needs to setup AVD (android emulator) .This is what brings your application in mobile phone environment.
  8.  Navigate window – AVD Manager – create your own AVD.
  9. Please note I don’t make details on above steps cause they are clearly documented in official website. But this process still can be troublesome. So I just mentioned the correct order and areas where you can go wrong. (Setting up and configuration is nightmare mostly )
That’s all. Then make sure and confirm your work by creating simple hello world application.

File – new – project – android project
Here you go.  You’re ready to code an application. We will start from beginner level application go around simple http requests . (GET / POST  etc)

My Simple REST API 

Well I have my own simple public REST API developed with php for my testings . You can also use them for testing.
Will start from service name “legendsincricket”.


This will give you following json string .

{"people": [{"id":"1","name":"Mahela Jayawardhane","country":"Sri Lanka"},{"id":"2","name":"Dale Steyn","country":"South Africa"},{"id":"3","name":"Shane Bond","country":"New Zealand"},{"id":"4","name":"Tendulkar","country":"India"},{"id":"5","name":"Saeed Anwar","country":"Pakistan"},{"id":"6","name":"Bryan Lara","country":"West Indies"}]}

Open eclipse
File – new – project – android project
Give a project name “ My favorite Cricketers “  and  select a class path .
Enter package name eg – com.hasitha.test
Expand your project from left hand side panel.
Find src/yourpackagename/activity.java
This is a file your going to code .
Android application is actually a collection of activities. So what you doing is coding a set of separate activites .
In root you will find file name AndroidManifest.xml. This is where you put all the root level settings related to app.
Find res/layout/main.xml file. This is where you create your theme layout with information of the all the controllers in application.

Lets Start coding

Import following packages on top of activity.java  file just bellow the package name .
These are related to handle UI / http web requests / common tasks like IO operations
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

These I use for format the json data .( All inbuilt . How awesome )

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.InputStream;
import org.json.JSONArray;
import java.io.BufferedReader;
Note that I used onclick event so I used OnClickListener here
public class HelloWorldActivity extends Activity implements OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.my_button).setOnClickListener(this);
    }

This is Where I implement onclick .
    @Override
       public void onClick(View arg0) {
              Button b = (Button)findViewById(R.id.my_button);
              b.setClickable(false);
              new LongRunningGetIO().execute();
       }
      
       private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
             
              protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
              InputStream in = entity.getContent();
                StringBuffer out = new StringBuffer();
                int n = 1;
                while (n>0) {
                    byte[] b = new byte[4096];
                    n =  in.read(b);
                    if (n>0) out.append(new String(b, 0, n));
                }
                return out.toString();
           }
             
Service call  with web http requests .
              @Override
              protected String doInBackground(Void... params) {
                      HttpClient httpClient = new DefaultHttpClient();
                      HttpContext localContext = new BasicHttpContext();
             HttpGet httpGet = new HttpGet("http://69.161.150.23/RestAPI/api/legendsincricket");
             String text = null;
             try {
                   HttpResponse response = httpClient.execute(httpGet, localContext);
                   HttpEntity entity = response.getEntity();
                   text = getASCIIContentFromEntity(entity);
             } catch (Exception e) {
               return e.getLocalizedMessage();
             }
             return text;
              }     
             
Formatting the output json data with inbuilt functions . Please note I first convert full json string into json object and then filter “people” array from  that object .
Service returns  few records so I looped through result array .


Finally copy the formatted string with  new line to editview using settext function.
              protected void onPostExecute(String results) {
                    
                     String tempString="";
                     if (results!=null) {
                          
                           try {
                                  JSONObject json=new JSONObject(results);
                                  JSONArray jsonArray=json.getJSONArray("people");

                                   for(int i=0;i<jsonArray.length();i++)
                                 {

                                          tempString +="Name : "+jsonArray.getJSONObject(i).getString("name")+" Country : "+ jsonArray.getJSONObject(i).getString("country")+"\n";

                                          
                                 }
                                 
                                 
                                 
                           } catch (JSONException e) {
                                  // TODO Auto-generated catch block
                                  e.printStackTrace();
                           }

                          
                          

                          
                           EditText et = (EditText)findViewById(R.id.my_edit);
                           et.setText(tempString);
                     }
                     Button b = (Button)findViewById(R.id.my_button);
                     b.setClickable(true);
              }
    }
}

Important : Put this line in your AndroidManifest.xml file  under androidminsdk tag . 
<uses-permission android:name="android.permission.INTERNET"/>  . This enable your app to deal with http requests.

I used one button and one edit view in my UI. I have attached the screenshot of final application on top.
Please keep in mind; you cant use locally hosted services with IP 127.0.0.1. Reason is android AVD is your local host in this case and it starts finding your services along with it. Use different IP address.
I know my article is not organized and clean. But I’m pretty sure it is well fitted with any programmer who can understand programming concepts well.
I covered full round trip here with in just few hours of work.
Do some icing stuff for the interface if you need.
Ill come up with complete app includes get / post / put in near future.
Good luck guys! Cheers!