In this tutorial, I will show you some example of retrieving data from webservice that return a json format. See output below.
Create a separate class and named it JSONParser.java. See code below!
package com.example.retrieveapi;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Next is in your MainActivity.java. See code below!.
package com.example.retrieveapi;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
JSONArray contacts = null;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
private Runnable search, returnRes;
private ProgressDialog m_ProgressDialog = null;
ArrayList<HashMap<String, String>> list;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
search = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(2000);
runOnUiThread(returnRes);
}catch (Exception ex){
ex.printStackTrace();
}
}
};
Thread thread = new Thread(null, search, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(this,"Please wait...", "Connecting...", true);
list = new ArrayList<HashMap<String,String>>();
returnRes = new Runnable() {
@Override
public void run() {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try{
contacts = json.getJSONArray(TAG_CONTACTS);
//Toast.makeText(getApplicationContext(), Integer.toString(contacts.length()), Toast.LENGTH_SHORT).show();
for(int i=0; i <= contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("email", email);
map.put("address", address);
map.put("gender", gender);
map.put("mobile", mobile);
map.put("home", home);
map.put("office", office);
list.add(map);
}
}catch(Exception e){
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_item,
new String[] {TAG_ID, TAG_NAME, TAG_ADDRESS, TAG_EMAIL, TAG_GENDER, TAG_PHONE_HOME, TAG_PHONE_MOBILE, TAG_PHONE_OFFICE },
new int[] {R.id.tv_id, R.id.tv_name, R.id.tv_address, R.id.tv_email, R.id.tv_gender, R.id.tv_hide_home, R.id.tv_hide_mobile, R.id.tv_hide_office});
ListView lv = getListView();
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
String tv_num1 = ((TextView) view.findViewById(R.id.tv_hide_mobile)).getText().toString();
String tv_num2 = ((TextView) view.findViewById(R.id.tv_hide_home)).getText().toString();
String tv_num3 = ((TextView) view.findViewById(R.id.tv_hide_office)).getText().toString();
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Contact");
alertDialog.setMessage("Mobile: "+tv_num1+"\n"+"Home: "+tv_num2+"\n"+"Office: "+tv_num3);
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
dialog.dismiss();
}
});
// Showing Alert Message
alertDialog.show();
}
});
m_ProgressDialog.dismiss();
}
};
}
}
And I have 3 XML layout here. Just see code below!
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl_main"
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" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Mobile" />
<TextView
android:id="@+id/tv_num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/tv_num1"
android:text="Home" />
<TextView
android:id="@+id/tv_num3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tv_num2"
android:layout_below="@+id/tv_num2"
android:text="Office" />
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp" >
<TextView
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="ID" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv_id"
android:layout_alignBottom="@+id/tv_id"
android:layout_alignParentLeft="true"
android:text="NAME" />
<TextView
android:id="@+id/tv_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tv_name"
android:layout_below="@+id/tv_name"
android:text="Address" />
<TextView
android:id="@+id/tv_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/tv_address"
android:text="Email" />
<TextView
android:id="@+id/tv_gender"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/tv_email"
android:layout_below="@+id/tv_email"
android:text="Gender" />
<TextView
android:id="@+id/tv_hide_mobile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv_gender"
android:layout_alignBottom="@+id/tv_gender"
android:layout_toRightOf="@+id/tv_address"
android:visibility="gone"
android:textSize="5sp"
android:text="Mobile" />
<TextView
android:id="@+id/tv_hide_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv_hide_mobile"
android:layout_alignBottom="@+id/tv_hide_mobile"
android:layout_toRightOf="@+id/tv_hide_mobile"
android:textSize="5sp"
android:visibility="gone"
android:text="Home" />
<TextView
android:id="@+id/tv_hide_office"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tv_hide_home"
android:layout_alignBottom="@+id/tv_hide_home"
android:layout_toRightOf="@+id/tv_hide_home"
android:textSize="5sp"
android:visibility="gone"
android:text="Office" />
</RelativeLayout>
And lastly in your AndroidManifest.xml. See code below!
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.retrieveapi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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.example.retrieveapi.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>
No comments:
Post a Comment