100% found this document useful (1 vote)
126 views

Web Service - Android

The document discusses how to call a web service from an Android application. It provides steps to encode and decode JSON, create an Android app with Java files to handle background tasks, responses, and displaying a custom dialog. The app communicates with a remote server to send and receive data using an asynchronous task and notifies the user with dialogs.

Uploaded by

tijuantony
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
126 views

Web Service - Android

The document discusses how to call a web service from an Android application. It provides steps to encode and decode JSON, create an Android app with Java files to handle background tasks, responses, and displaying a custom dialog. The app communicates with a remote server to send and receive data using an asynchronous task and notifies the user with dialogs.

Uploaded by

tijuantony
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

How to call Web Service from Android ?

| Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

Sharing a knowledge is first step of success

How to call Web Service from Android ?


MAY 27, 2013 CHINTAN KHETIYA LEAVE A COMMENT About This is these first ads (h example p://en.wordpress.com/about-these-ads/) 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 its 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 ?

1 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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);

2 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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 ve java les to maintain this app. Android_WebService.java [Task - Handle events and views] AsyncTaskCompleteListener.java [Task - Interface for use response in other le] 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 le 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 le 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);

3 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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("http://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); }

4 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

@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 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. } }

5 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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.CONNECTIVIT 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

6 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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) {

7 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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;

8 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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(); } });

9 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

} 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_tex alert_infromation_text.setText(Msg); pb = (ProgressBar) findViewById(R.id.progressBar1); no.setVisibility(View.GONE); } }

Function.java All data member and function are wrien 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");

10 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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;

11 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

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(); } } }

Dont 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

12 of 13

25-01-2014 17:20

How to call Web Service from Android ? | Android Hub

http://chintankhetiya.wordpress.com/2013/05/27/83/

You May Like


1.

Blog at WordPress.com. | The Crafty Theme. Follow

Follow Android Hub


Powered by WordPress.com

13 of 13

25-01-2014 17:20

You might also like