Here you will get android json parsing from url example.
What I will do here?
- First fetch json string from url.
- Parse the json data and display in listview.
The data contains a json array with some fruits name as shown below.
{ "fruits":[ "Apple", "Apricot", "Avocado", "Banana", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry", "Boysenberry", "Currant", "Cherry", "Cherimoya", "Cloudberry", "Coconut", "Cranberry", "Custard apple", "Damson", "Date", "Dragonfruit", "Durian", "Elderberry", "Feijoa", "Fig", "Goji berry", "Gooseberry", "Grape", "Raisin", "Grapefruit", "Guava" ] }
Also Read: Picasso Android Tutorial – Load Image from URL
Android JSON Parsing From URL Example
Create a new android studio project with package name com.jsonparsing.
As we are fetching data from internet so we have to add internet access permission. Add following line of code in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
I am using volley library in this example. It is a network library that is used to fetch data from server or internet. So add it to your project by adding following line of code in app level build.gradle file under dependencies section. After that sync the project.
compile 'com.android.volley:volley:1.0.0'
The following code is responsible for fetching json data from url in the form of json string using volley library.
StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String string) { parseJsonData(string); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } });
- When data is fetched successfully then onResponse() method is called.
- If there is any error while fetching data then onErrorResponse() is called and an error message is displayed in toast.
After creating the volley request we have to add it to request queue.
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this); rQueue.add(request);
Now comes the parsing part. The parseJsonData() method contains the code to parse the json string.
void parseJsonData(String jsonString) { try { JSONObject object = new JSONObject(jsonString); JSONArray fruitsArray = object.getJSONArray("fruits"); ArrayList al = new ArrayList(); for(int i = 0; i < fruitsArray.length(); ++i) { al.add(fruitsArray.getString(i)); } ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, al); fruitsList.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } dialog.dismiss(); }
- First json string is parsed to json object. From this object a json array with name fruits is fetched.
- Now each fruit is fetched from json array one by one inside loop and added to an arraylist.
- Finally this list of fruits is assigned to listview using an adapter.
Below I have shared the full source code.
activity_main.xml
<?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" 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="com.jsonparsing.MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/fruitsList"/> </RelativeLayout>
MainActivity.java
package com.jsonparsing; import android.app.ProgressDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { ListView fruitsList; String url = "http://thecrazyprogrammer.com/example_data/fruits_array.json"; ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fruitsList = (ListView)findViewById(R.id.fruitsList); dialog = new ProgressDialog(this); dialog.setMessage("Loading...."); dialog.show(); StringRequest request = new StringRequest(url, new Response.Listener<String>() { @Override public void onResponse(String string) { parseJsonData(string); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this); rQueue.add(request); } void parseJsonData(String jsonString) { try { JSONObject object = new JSONObject(jsonString); JSONArray fruitsArray = object.getJSONArray("fruits"); ArrayList al = new ArrayList(); for(int i = 0; i < fruitsArray.length(); ++i) { al.add(fruitsArray.getString(i)); } ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, al); fruitsList.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } dialog.dismiss(); } }
Screenshots
You can ask your queries related to above android json paring from url example.
Nice
Absolutely the best tutorial about json.
Thanks
What if i only want to get an item form an array? what must i do? please help!
Great Tutorial Keep the Good Work.
How can i see with your code… “ñ” and “´” ?? In spanish is tipical use Ñ and á é í ó ú
only first object is shown in output
code is not working!! please put correct code here