JSON is one of the best method to provide data in android from web application. So I am discussing here how to parse a JSON response from a URL and use it, in this tutorial Android JSON Parsing From URL. JSON data has square and curly brackets which denotes JSON array and JSON object simultaneously.
Creating Project:
Create a new project in Eclipse IDE as “Read JSON from URL” with package com.tricks.readjsonfromurl. Now Create the main Activity as “MainActivity” and the main Layout as activity_main.
Manifest:
Just add a permission “android.permission.INTERNET” to the manifest file for access external url or address.
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tricks.readjsonfromurl" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" 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.tricks.readjsonfromurl.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>
Creating Layout:
The main layout for our project is “activity_main” which has three TextView as Label and other three for display the website ID, Name and URL of JSON object from the URL.
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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:textStyle="bold" android:textSize="18sp" android:text="@string/info" /> <TextView android:id="@+id/wid" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="75dp" android:layout_marginTop="45dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="45dp" android:textStyle="bold" android:text="@string/wid" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/wid" android:layout_marginLeft="75dp" android:layout_marginTop="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/wid" android:layout_marginTop="30dp" android:text="@string/name" android:textStyle="bold" /> <TextView android:id="@+id/url" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/name" android:layout_marginLeft="75dp" android:layout_marginTop="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/name" android:layout_marginTop="30dp" android:textStyle="bold" android:text="@string/url" /> </RelativeLayout>
Creating String Values:
You should create string constants values in re/values/strings.xml to use in layout.
strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Read Json From URL</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <string name="info">Website Information from URL</string> <string name="wid">ID</string> <string name="name">Name</string> <string name="url">Website</string> </resources>
Creating Activity:
Now to get JSON data from the URL we need to create a HttpClient and get the data from URL “http://demos.tricksofit.com/files/json.php”. If you have only JSON object you can use JSONObject json = new JSONObject(str);, If you have JSON Array then you can use JSONArray jArray = new JSONArray(str);. In MainActivity we will get the ID, Name and URL of the first object and displaying it on the layout.
MainActivity.java package com.tricks.readjsonfromurl; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import android.os.StrictMode; import android.app.Activity; import android.view.Menu; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .penaltyDialog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll() .penaltyLog() .build()); TextView wid = (TextView) findViewById(R.id.wid); TextView name = (TextView) findViewById(R.id.name); TextView url = (TextView) findViewById(R.id.url); JSONObject json = null; String str = ""; HttpResponse response; HttpClient myClient = new DefaultHttpClient(); HttpPost myConnection = new HttpPost("http://demos.tricksofit.com/files/json.php"); try { response = myClient.execute(myConnection); str = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try{ JSONArray jArray = new JSONArray(str); json = jArray.getJSONObject(0); wid.setText(json.getString("id")); name.setText(json.getString("name")); url.setText(json.getString("url")); } catch ( JSONException e) { e.printStackTrace(); } } @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; } }
JSON Data :
[ { "id": "01", "name": "Tricks Of IT", "url": "www.tricksofit.com" }, { "id": "02", "name": "Demos Tricks Of IT", "url": "www.demos.tricksofit.com" } ]
Output: