Android Development – Parsing JSON Data from a URL
JSON is very light weight, structured, easy to parse and much human readable. JSON is best alternative to XML when your android app needs to interchange data with your server. In this simple tutorial I am going to show you how to parse a JSON response from a URL and display it in a ListView
Before we start
- Make sure you have properly setup the Android SDK, AVD for Testing the Application.
- Create a New project in Android Studio / Eclipse IDE with the package as “com.carlofontanos.parsejsondatafromurl“. Create the Main Activity as “MainActivity” and the main Layout as “activity_main”.
For this example, the JSON data we are going to parse can be found here: https://carlofontanos.com/api/tutorials.php?data=all
MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | package com.carlofontanos.parsejsondatafromurl; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import android.os.AsyncTask; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends AppCompatActivity { ListView listView; ArrayList<String> tutorialList = new ArrayList<String>(); private final static String URL = "https://carlofontanos.com/api/tutorials.php?data=all"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new FetchDataTask().execute(URL); } private class FetchDataTask extends AsyncTask<String, Void, String>{ @Override protected String doInBackground(String... params) { InputStream inputStream = null; String result= null; HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(params[0]); try { HttpResponse response = client.execute(httpGet); inputStream = response.getEntity().getContent(); // convert inputstream to string if(inputStream != null){ result = convertInputStreamToString(inputStream); Log.i("App", "Data received:" +result); } else result = "Failed to fetch data"; return result; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String dataFetched) { //parse the JSON data and then display parseJSON(dataFetched); } private String convertInputStreamToString(InputStream inputStream) throws IOException{ BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream)); String line = ""; String result = ""; while((line = bufferedReader.readLine()) != null) result += line; inputStream.close(); return result; } private void parseJSON(String data){ try{ JSONArray jsonMainNode = new JSONArray(data); int jsonArrLength = jsonMainNode.length(); for(int i=0; i < jsonArrLength; i++) { JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); String postTitle = jsonChildNode.getString("post_title"); tutorialList.add(postTitle); } // Get ListView object from xml listView = (ListView) findViewById(R.id.list); // Define a new Adapter ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, tutorialList); // Assign adapter to ListView listView.setAdapter(adapter); }catch(Exception e){ Log.i("App", "Error parsing data" +e.getMessage()); } } } } |
actvitiy_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?xml version="1.0" encoding="utf-8"?> <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" tools:context="${relativePackage}.${activityClass}" > <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/list" android:textColor="#000000" android:layout_height="wrap_content" android:layout_width="match_parent"> </ListView> </LinearLayout> </RelativeLayout> |
Android recently made a variety of system changes and API behavior changes, they have removed the built in HTTPClient due to security reasons, but you can still use it by downloading the latest HTTPClient library from here https://hc.apache.org/downloads.cgi – include the jar files into your app/libs folder then add the following dependency into your gradle file:
1 2 3 | dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) } |
You might also get a META-INF error when running the app, to fix that simply include the following packing options in your gradle file:
1 2 3 4 5 6 7 8 9 10 11 12 | android { packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/notice.txt' exclude 'META-INF/ASL2.0' } } |
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.
1 | <uses-permission android:name="android.permission.INTERNET" /> |
Run the Program
Everything’s set, now it’s time to run your program! You should be able to see a ListView similar to the screenshot bellow:
—
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me