2014年1月21日火曜日

Quick Guide to Android Networking by Request Message from Server

A quick guide to programming Android request Server and getting the message. On this guide, I am going to show you how to getting message "hello! I am server." and show it on Android.



On Server side

Before programming android, prepare some simple php script on server. 
<?php
    echo "hello! I am server";
?>

Script it as simple as you can.

On Android side

Android is quiet complicated with Internet. You needs to enable android to access to internet and work your internet thread on background. Before we get start with our tutorial, copy the code below and debug it. It is always simple to understand if you get the things work first.

package com.example.apps1;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

 private TextView mTextView;
 private static final String TAG = MainActivity.class.getName();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
               
        mTextView = new TextView(this);
        addContentView(mTextView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        new ConnectToServer().execute();
        
    }
    
    public class ConnectToServer extends AsyncTask<Void,Void,String>{

  @Override
  protected String doInBackground(Void... params) {
   // replace the url to your own   
   return HttpRequest("http://path_to_server/");
  }
  
  @Override
  protected void onPostExecute(String result){
   if(result == null){
    mTextView.setText("Failed to connecting to server");
   }else{
    mTextView.setText(result);
   }   
  }
  
  public String HttpRequest(String url) 
  {
       
    
       
    DefaultHttpClient client = new DefaultHttpClient();
    HttpResponse response = null;
      
    try{          
     HttpGet httpGet = new HttpGet(url);     
     response = client.execute(httpGet);     
            
     return EntityUtils.toString(response.getEntity());

    }catch(ClientProtocolException e){
     Log.e(TAG,"ClientProtocolException : "+e);
    }catch(IOException e){
     Log.e(TAG,"IOException : "+e);
    }      
   
    return null;
   }
     
    }    
}



Replace the url "http://path_to_server" to your own in HttpRequest.

Don't debug it, we haven't done yet. As I mentioned above, you need to configure android to able to access internet. What you needs to do is simple, go to your_project_directory and open AndroidManifest.xml

Add following uses-permission to in front of <uses-sdk> tag
<uses-permission android:name="android.permission.INTERNET" />

Then, debug it and you will see the requested message from server.

Explanation

There are 2 things you need to be careful when programming across internet.

  1. Networking thread must be on background
  2. Configure internet permission in AndroidManifest.xml


Android is doing a good job for developer, there are built-in background thread method prepared by Android called AsyncTask.

AsyncTask easy us to doing background task coding by put all the background code in doInBackground method. On the code above, HttpRequest method is the internet task and you will find it I put it on doInBackground method. It means the all the task in HttpRequest will be carried out in background thread.


onPostExecute method is a callback method for background thread. After HttpRequest getting the messages, it needs to show it on UI. Here's where onPostExecute comes, the message returned by HttpRequest method is assign to onPostExecute 1st parameter "result". TextView set text of 1st parameter result.

@Override
protected String doInBackground(Void... params) {
 // doing all networking thread here
 // 
 // 1st parameter of HttpRequest is the url to server. Replace the url to your own
 return HttpRequest("http://path_to_server/");
}

@Override
protected void onPostExecute(String result){
 // 1st parameter result is the result returned by HttpRequest which doInBackground
 if(result == null){
  mTextView.setText("Failed to connecting to server");
 }else{
  mTextView.setText(result);
 }   
}

// Doing all Networking task, if failed to get message from server, it will return null  
// 
public String HttpRequest(String url){
     
  DefaultHttpClient client = new DefaultHttpClient();
  HttpResponse response = null;
    
  try{          
   HttpGet httpGet = new HttpGet(url);     
   response = client.execute(httpGet);     
          
   return EntityUtils.toString(response.getEntity());

  }catch(ClientProtocolException e){
   Log.e(TAG,"ClientProtocolException : "+e);
  }catch(IOException e){
   Log.e(TAG,"IOException : "+e);
  }      

  return null;
 }



After coding AsyncTask method, you needs to execute it by
new ConnectToServer().execute();


Be caution here, AsyncTask is easy but it can only be executed one time in single Activity.

It means if you execute AsnycTask for twice, exception will be thrown and you will get errors.
Luckily, Android have prepared another method called ExecutorService. It allows multiple network task can be executed in single activity.

Check it out with my next post, if you are interesting with it.

End

Thank you for reading and hope my blog will help you.

0 件のコメント:

コメントを投稿