In this post I will be showing how to use the JSON data produced in the web service we made in my previous post in an Android App. The app will be having a listview in which the ASP.NET JSON data will be loaded. Please note that you must be having the Webservice from previous post hosted in Windows IIS or refer this post. To see how to can host the ASP.NET website refer this post.
Make the new Android application or just open your current Android application project in Eclipse ADT or Android Studio.
The XMLs file
Two files :
- mydata.xml
- rows.xml
mydata.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:id="@+id/lst" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:divider="#fff" android:dividerHeight="1dp" > </ListView> <ProgressBar android:id="@+id/pbbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> <TextView android:id="@+id/txtinfo" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Just a moment" android:textColor="#707070" android:textSize="25sp" /> </LinearLayout>
rows.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#0f80f0" android:orientation="vertical" android:padding="7dp" > <TextView android:id="@+id/txtcityname" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:text="MUMBAI" android:textSize="20sp" android:typeface="sans" /> <TextView android:id="@+id/txtcountryname" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#fff" android:text="INDIA" android:textSize="16sp" android:typeface="sans" /> </LinearLayout>
JAVA files
Make two new classes :
- JsonParser.java
- JSONActivity.java
JsonParser.java
This class will help us to get the data from Webservice we made
package com.example.samples; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; public class JsonParser { public String getJSON(String url) { StringBuilder builder = new StringBuilder(); String line; String responseMessage; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse httpResponse = httpClient.execute(httpGet); StatusLine statusLine = httpResponse.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity httpEntity = httpResponse.getEntity(); InputStream inputStream = httpEntity.getContent(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); while ((line = bufferedReader.readLine()) != null) { builder.append(line); } } responseMessage = builder.toString(); } catch (Exception ex) { responseMessage = ex.getMessage().toString(); } return responseMessage; } }
JSONActivity.java
This is our activity class file
package com.example.samples; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class JSONActivity extends ActionBarActivity { JsonParser jsonparser; ProgressBar pbbar; JSONObject jobj; ListView lst; TextView txtinfo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mydata); lst = (ListView) findViewById(R.id.lst); pbbar = (ProgressBar) findViewById(R.id.pbbar); txtinfo = (TextView) findViewById(R.id.txtinfo); pbbar.setVisibility(View.GONE); txtinfo.setVisibility(View.GONE); jsonparser = new JsonParser(); jobj = new JSONObject(); LoadJS js = new LoadJS(); js.execute(""); } private class LoadJS extends AsyncTask<String, String, String> { String resultedData = null; @Override protected String doInBackground(String... params) { try { String h = "http://192.168.0.100:100//webservices/MyService.asmx/HelloJSON"; resultedData = jsonparser.getJSON(h); } catch (Exception ex) { resultedData = "There's an error, that's all I know right now.. :("; } return resultedData; } @Override protected void onPreExecute() { pbbar.setVisibility(View.VISIBLE); txtinfo.setVisibility(View.VISIBLE); } @Override protected void onPostExecute(String r) { pbbar.setVisibility(View.GONE); txtinfo.setVisibility(View.GONE); try { ArrayList<Map<String, String>> data = new ArrayList<Map<String, String>>(); JSONArray jarray = new JSONArray(r); for (int i = 0; i < jarray.length(); i++) { Map<String, String> datanum = new HashMap<String, String>(); jobj = jarray.getJSONObject(i); datanum.put("City", jobj.getString("Name")); datanum.put("Country", jobj.getString("Country")); data.add(datanum); } String[] from = { "City", "Country" }; int[] views = { R.id.txtcityname, R.id.txtcountryname }; final SimpleAdapter ADA = new SimpleAdapter(JSONActivity.this, data, R.layout.rows, from, views); lst.setAdapter(ADA); } catch (Exception ex) { Toast.makeText(JSONActivity.this, "error", Toast.LENGTH_LONG) .show(); txtinfo.setVisibility(View.VISIBLE); txtinfo.setText(ex.getMessage().toString()); } } } }
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.samples" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".JSONActivity" android:label="@string/app_name" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>