Last updated on January 9th, 2020 at 12:27 pm
Android application most of time need to load data from webservice. In this post i will explain you how to load data from webservice which is in JSON format. JSON (JavaScript Object Notation) is a lightweight data-interchange format. Which is very to read and write and also very easy to parse data between application. JSON is a best alternative to XML.
Sample JSON
This is a simple JSON formatted data which we going to parse in our application. This JSON conatin basic information like Name, email, etc..
{ "Name": "Aneh Thakur", "email": "[email protected]", "status": "Love Think and Code!", "facebook": "anehkumar" }
Square and Curly brackets ( [ { )
JSON nodes always start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So when we need to access data from JSON we need specific method.
If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.
Start your New Android Project
1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. I had left my main activity name as MainActivity.java .
2. As we are fetching the JSON by making HTTP calls, we need to add INTERNET permission in our AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.
<uses-permission android:name="android.permission.INTERNET" />
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.loadservice" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="19" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.loadservice.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
3. Now open your activity_main.xml inside res ⇒ layout folder and create a button through which we can load our service on click. And display result on it as shown below.
activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="24dp" android:text="Load!" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="34dp" android:text="Load your webservice" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView2" android:layout_width="400dp" android:layout_height="wrap_content" android:layout_below="@+id/button1" android:layout_centerHorizontal="true" android:layout_marginTop="30dp" /> <RelativeLayout android:id="@+id/serviced" android:layout_width="fill_parent" android:layout_height="match_parent" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:visibility="gone" > <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/name" android:layout_alignParentLeft="true" android:text="Name" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/textView3" android:layout_marginTop="26dp" android:text="Email" /> <TextView android:id="@+id/email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView4" android:text="Email" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/status" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/textView6" android:text="Status" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/fb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:layout_marginBottom="56dp" android:text="facebook" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/textView8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/fb" android:layout_alignBottom="@+id/fb" android:layout_alignParentLeft="true" android:text="Facebook" /> <TextView android:id="@+id/textView6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:text="Status" /> <TextView android:id="@+id/sname" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="Name" android:textAppearance="?android:attr/textAppearanceLarge" /> </RelativeLayout> </RelativeLayout>
4. Now open you MainActivity.java inside src ⇒MainActivity.java. In this file we load our web service and display result to main screen.
MainActivity.java package com.loadservice; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Button GetServerData = (Button) findViewById(R.id.button1); GetServerData.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Server Request URL String serverURL = "http://demo.trinityblog.in/downloads/android/service.php"; // Create Object and call AsyncTask execute Method new LoadService().execute(serverURL); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } // Class with extends AsyncTask class private class LoadService extends AsyncTask<String, Void, Void> { private final HttpClient Client = new DefaultHttpClient(); private String Content; private String Error = null; private final String TAG = null; String name = null; private ProgressDialog Dialog = new ProgressDialog(MainActivity.this); TextView uiUpdate = (TextView) findViewById(R.id.textView2); protected void onPreExecute() { // NOTE: You can call UI Element here. // UI Element uiUpdate.setText(""); Dialog.setMessage("Loading service.."); Dialog.show(); } // Call after onPreExecute method protected Void doInBackground(String... urls) { try { // NOTE: Don't call UI Element here. HttpGet httpget = new HttpGet(urls[0]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); Content = Client.execute(httpget, responseHandler); } catch (ClientProtocolException e) { Error = e.getMessage(); cancel(true); } catch (IOException e) { Error = e.getMessage(); cancel(true); } return null; } protected void onPostExecute(Void unused) { // Close progress dialog Dialog.dismiss(); Log.e(TAG, "------------------------------------- Output: " + Content); try { // Load json data and display JSONObject json = new JSONObject(Content); TextView name = (TextView)findViewById(R.id.sname); name.setText(json.getString("Name")); TextView email = (TextView)findViewById(R.id.email); email.setText(json.getString("email")); TextView status = (TextView)findViewById(R.id.status); status.setText(json.getString("status")); TextView face = (TextView)findViewById(R.id.fb); face.setText(json.getString("facebook")); RelativeLayout serv = (RelativeLayout)findViewById(R.id.serviced); serv.setVisibility(View.VISIBLE); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } uiUpdate.setText("Raw Output : " + Content); } } }
To load data from webservice i am using HttpClient. I also create a New private class which perform AsynTask to load data in Background.
LoadService()
And call that class in onclicklistener. So when ever user press the button we load the data from service
final Button GetServerData = (Button) findViewById(R.id.button1); GetServerData.setOnClickListener(new OnClickListener() { public void onClick(View v) { // Server Request URL String serverURL = "http://demo.trinityblog.in/downloads/android/service.php"; // Create Object and call AsyncTask execute Method new LoadService().execute(serverURL); } });
Parsing JSON Data
After creating private class which extends AsyncTask we make http calls on background thread. Add the following method in your main activity class.
private class LoadService extends AsyncTask<String, Void, Void> { ....... }
In onPreExecute() method where we showed a progress dialog before making actual http call.
protected void onPreExecute() { // NOTE: You can call UI Element here. uiUpdate.setText(""); Dialog.setMessage("Loading service.."); Dialog.show(); }
In doInBackground() method, I call HttpGet to load data using get method and pass my url to load
protected Void doInBackground(String... urls) { try { // NOTE: Don't call UI Element here. HttpGet httpget = new HttpGet(urls[0]); ResponseHandler<String> responseHandler = new BasicResponseHandler(); Content = Client.execute(httpget, responseHandler); } catch (ClientProtocolException e) { Error = e.getMessage(); cancel(true); } catch (IOException e) { Error = e.getMessage(); cancel(true); } return null; }
In onPostExecute() method we can display our loaded data according to layout.
Also note that I have used getJSONArray() or getJSONObject() method depending on the type of node.
protected void onPostExecute(Void unused) { // Close progress dialog Dialog.dismiss(); Log.e(TAG, "------------------------------------- Output: " + Content); try { // Load json data and display JSONObject json = new JSONObject(Content); TextView name = (TextView)findViewById(R.id.sname); name.setText(json.getString("Name")); TextView email = (TextView)findViewById(R.id.email); email.setText(json.getString("email")); TextView status = (TextView)findViewById(R.id.status); status.setText(json.getString("status")); TextView face = (TextView)findViewById(R.id.fb); face.setText(json.getString("facebook")); RelativeLayout serv = (RelativeLayout)findViewById(R.id.serviced); serv.setVisibility(View.VISIBLE); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } uiUpdate.setText("Raw Output : " + Content); }
Thank you!.