How to call Web Service from Android ?

This is first example about web service in android written by me.This will show you how android will communicate with remote server and fetch and send data to server.

List of things that is included in this post :

  • What is Web Service ?
  • How it’s works?
  • How to Decode JSON?
  • How to create Custom Dialog ?
  • How to manage  AsyncTask ?

Note: I have wrote separate post of Custom Dialog and AsynTask So, i will not explain in depth.

What are Web Service ?

  • Web services are application components
  • Web services communicate using open protocols
  • Web services are self-contained and self-describing
  • Web services can be discovered using UDDI
  • Web services can be used by other applications
  • XML is the basis for Web services

How does it works ?

How its’ works ?

How to Encode & Decode JSON in android?

Encode :

// Create JSON obj 
JSONObject json = new JSONObject();

// encode your json value 
json.put("user_name", "test");
json.put("password", "test123");

Decode

  • Decode JSON Object
  • Decode JSON Array

Decode Object 

JSONObject json_data = new JSONObject(response);
String value = json_data.getString("status");

Decode Array 

JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject json_data = jArray.getJSONObject(i);
// add to list
User_ID.add(json_data.getString("user_id"));
}

Now we are able to  encode and decode our value in JSON so now we are going to build android app that will
simply connect with server and send and receive simple value.

We have main five java files to maintain this app.

  • Android_WebService.java  [Task – Handle events and views]
  • AsyncTaskCompleteListener.java [Task – Interface for use response in other file]
  • Background_Task.java [Task – Manage Background task using  AsynTask]
  • Custom_alert_DialogClass.java [Task – Custom alert dialog to update UI]
  • Function.java [Task – All Global function and data member]

we are going to start with all one by one java file with comments so it would be easy to use and understand.

Android_WebService.java

This class will prepare the view and manage action like OnClick and Listener.Also we can say that this is root becasue reset of all other file are handleing in this class.

public class Android_WebService extends Activity implements
AsyncTaskCompleteListener {

Function fun;
Background_Task bTask;
Button call_ws;
String User_Name = null;
String TAG = "Android_WebService_Error";
ArrayList<String> User_Id = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Set_View();

call_ws.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try {
// check for internet connection
if (isNetworkAvailable() == true) {

// clear older parms value
fun.URL_Params.clear();

// add your params here

// fun.URL_Params.add(new
// BasicNameValuePair("key_value",""));

// pass your parms to constructor
bTask = new Background_Task(fun.URL_Params,
Android_WebService.this);

// show a message while loader is loading
fun.Alert_Msg = "Please Wait...\nWe are Authenticating your details";
fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

// call web service in asyn class
bTask.execute("https://chintankhetiya.wordpress.com/");

} else {
fun.Alert_Msg = "Sorry..\n Try to connect Internet first.";
fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
}
} catch (Exception e) {
// TODO: handle exception
fun.Alert_Msg = "Sorry..\n Try to connect internet first.";
fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);
}
}
});

}

public void Call_My_Blog(View v) {
Intent intent = new Intent(Android_WebService.this, My_Blog.class);
startActivity(intent);

}

@Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
fun.Hide_Loader();
if (result != null) {

// call and edit below function as per your needs
/*
* Response_JSON_Object(result); Response_JSON_Array(result);
*/

fun.Alert_Msg = "congrats ..\n You have create web-service example successfully.";
fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
fun.Hide_Loader(); // when the task active then close the
// dialog
t.cancel(); // also just top the timer thread,
// otherwise, you may receive a crash report
}
}, fun.Dialog_Time_Limit); // after 2 second (or 2000
// miliseconds), the task will
// be active.

}

else {
fun.Alert_Msg = "Sorry..\n We are not able connect with Chintan Khetiya's Blog due to slow Internet Connction.\n Reset WI-FI or Try Later";
fun.Show_Loader(Android_WebService.this, fun.Alert_Msg);

final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
fun.Hide_Loader(); // when the task active then close the
// dialog
t.cancel(); // also just top the timer thread,
// otherwise, you may receive a crash report
}
}, fun.Dialog_Time_Limit); // after 2 second (or 2000
// miliseconds), the task will
// be active.

}

}

public String Response_JSON_Object(String Buffer_Response) {
try {
JSONObject json_data = new JSONObject(Buffer_Response);
User_Name = json_data.getString("User_Name").toString();
return User_Name;
} catch (Exception e) {
Log.e(TAG, "Json Object issue" + e);
}
return User_Name;

}

public ArrayList<String> Response_JSON_Array(String Buffer_Response) {
try {
JSONArray jArray = new JSONArray(Buffer_Response);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
// add to list
User_Id.add(json_data.getString("user_id"));
}

} catch (Exception e) {
// TODO: handle exception
Log.e(TAG, "Json array issue" + e);
}
return User_Id;
}

public void Set_View() {
fun = new Function(getApplicationContext());
call_ws = (Button) findViewById(R.id.call);

}

public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null
// otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
}

AsyncTaskCompleteListener.java

This is separate class to handle incoming parmas value form root class and run task in background thread.
It will redirect when task will complete.


public interface AsyncTaskCompleteListener {
// it will call when background process finish
public void onTaskComplete(String result);
}

Background_Task.java


public class Background_Task extends AsyncTask {

    public Activity activity;
    Context context;
    public AsyncTaskCompleteListener callback;
    ArrayList URL_Params = new ArrayList();
    Function fun = new Function();
    ProgressDialog Loader_Dialog;
    Custom_alert_DialogClass cad;

    public Background_Task(ArrayList URL_Params, Activity act) {
	this.URL_Params = URL_Params;

	this.activity = act;
	this.callback = (AsyncTaskCompleteListener) act;
    }

    @Override
    protected void onPreExecute() {
	super.onPreExecute();
	try {

	    Log.i("onPre", "call");
	} catch (Exception e) {
	    // TODO: handle exception
	    Log.e("onPre", "" + e);
	}

    }

    @Override
    protected String doInBackground(String... web_url) {
	try {
	    // this will send req in post
	    // here [0] mean URL & passing params
	    Log.i("onDO", "call");

	    fun.Send_Simple_Detail_To_Server(web_url[0], URL_Params);

	    Log.i("onDO", "SEND");

	    // this will get stream response
	    fun.Buffer_Response();
	    Log.i("onDO", "GET RES");

	} catch (Exception e) {
	    // TODO: handle exception
	    Log.e("onDo", "" + e);
	}

	return fun.Buffer_String_Response;
    }

    @Override
    protected void onPostExecute(String result) {
	super.onPostExecute(result);
	// check is dialog open ? THEN HIDE DIALOG
	try {
	    Log.i("onPOST", "DONE");
	    Log.i("onPOST", "" + result);

	    callback.onTaskComplete(result);
	} catch (Exception e) {
	    Log.e("onPost", "" + e);
	    // TODO: handle exception
	}

    }

}

Custom_alert_DialogClass.java

Custom Dialog to updating UI status so user get notify that what is going on.


public class Custom_alert_DialogClass extends Dialog {

    public Activity a;
    public String Msg;
    public Dialog d;
    public Button no;
    public Context context;
    public TextView alert_infromation_text;
    ProgressBar pb;
    LinearLayout exit_layout;

    public Custom_alert_DialogClass(Activity a, String Msg) {
	super(a);
	// TODO Auto-generated constructor stub
	this.a = a;
	this.Msg = Msg;

    }

    /**
     * Constructor for Custom_alert_DialogClass.java Called for initializing
     * object of Custom_alert_DialogClass.java.
     * 
     * @param function
     * @param alert_Msg
     */
    public Custom_alert_DialogClass(Context c, String alert_Msg) {
	// TODO Auto-generated constructor stub

	super(c);
	this.context = c;
	this.Msg = alert_Msg;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.custom_alert_dialog);
	Create_Alert_DialogView();

	no.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
		// TODO Auto-generated method stub
		dismiss();

		a.finish();

	    }
	});

    }

    public void Create_Alert_DialogView() {

	no = (Button) findViewById(R.id.Dailog_Exit);
	exit_layout = (LinearLayout) findViewById(R.id.exit_layout);
	exit_layout.setVisibility(View.GONE);
	alert_infromation_text = (TextView) findViewById(R.id.alert_infromation_text);
	alert_infromation_text.setText(Msg);
	pb = (ProgressBar) findViewById(R.id.progressBar1);
	no.setVisibility(View.GONE);
    }

}

Function.java

All data member and function are written here so it will easy to execute and understand.


public class Function {
    public ConnectivityManager cm;
    public NetworkInfo ni;
    public InputStream is;
    Context ctx;
    JSONObject jObjec = new JSONObject();
    String Buffer_String_Response = null;
    Custom_alert_DialogClass cad;
    public ArrayList URL_Params = new ArrayList();
    String Alert_Msg;
    long Dialog_Time_Limit = 3000;

    public Function(Context context) {
	this.ctx = context;
    }

    public Function() {

    }

    public void Send_JSON_Encode_Detail_To_Server(String URL, JSONObject jobj) {
	try {

	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(URL);
	    httppost.setHeader("Content-type", "application/json");
	    StringEntity se = new StringEntity(jobj.toString());
	    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
		    "application/json"));
	    httppost.setEntity(se);
	    HttpResponse response = httpclient.execute(httppost);
	    String temp = EntityUtils.toString(response.getEntity());
	    Log.i("tag", temp);

	} catch (ConnectTimeoutException e) {
	    Log.e("Timeout Exception: ", e.toString());

	} catch (SocketTimeoutException ste) {
	    Log.e("Timeout Exception: ", ste.toString());

	} catch (Exception e) {
	    Log.e("HTTP_Execption", "Error in http connection " + e.toString());

	}
    }

    public void Send_Simple_Detail_To_Server(String URL,
	    ArrayList nameValuePairs)

    {
	try {

	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(URL);
	    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	    HttpResponse response = httpclient.execute(httppost);
	    HttpEntity entity = response.getEntity();

	    is = entity.getContent();

	} catch (ConnectTimeoutException e) {
	    Log.e("Timeout Exception: ", e.toString());

	} catch (SocketTimeoutException ste) {
	    Log.e("Timeout Exception: ", ste.toString());

	} catch (Exception e) {
	    Log.e("HTTP_Execption", "Error in http connection " + e.toString());

	}
    }

    public void Buffer_Response() {
	try {
	    Buffer_String_Response = null;
	    BufferedReader reader = new BufferedReader(new InputStreamReader(
		    is, "iso-8859-1"), 8);
	    StringBuilder sb = new StringBuilder();
	    String line = null;
	    while ((line = reader.readLine()) != null) {
		sb.append(line + "\n");
	    }
	    is.close();
	    Buffer_String_Response = sb.toString();

	} catch (Exception e) {
	    Log.e("Loading Runnable Error converting result :", e.toString());

	}

    }

    public void Show_Loader(Activity a, String Text_Message) {

	cad = new Custom_alert_DialogClass(a, Text_Message);
	cad.show();
    }

    public void Hide_Loader()

    {
	if (cad != null && cad.isShowing()) {
	    cad.dismiss();
	}

    }

}

Don’t forget to update your manifest with Permission

uses-permission android:name="android.permission.INTERNET"
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE

Get Full Source code 

GitHub-download

14 thoughts on “How to call Web Service from Android ?

    1. You have to learn how to create web service in php using mysql database. Try to Google there are lots of example available.

      Like

  1. i want to connect my sql server to android without using php code. is any possibility are there please tell me

    Like

Leave a comment