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. If your app consuming XML data, you can always refer to Android XML Parsing Tutorial.

In this tutorial we are going to learn how to parse JSON in android using different ways, using java.net library and other third part libraries.

The Sample JSON

Following is the sample JSON that we are going to parse in this tutorial. This is very simple JSON which gives us list of contacts where each node contains contact information like name, email, address, gender and phone numbers.

You can get this JSON data by accessing https://api.androidhive.info/contacts/

{
    "contacts": [
        {
                "id": "c200",
                "name": "Ravi Tamada",
                "email": "ravi@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        {
                "id": "c201",
                "name": "Johnny Depp",
                "email": "johnny_depp@gmail.com",
                "address": "xx-xx-xxxx,x - street, x - country",
                "gender" : "male",
                "phone": {
                    "mobile": "+91 0000000000",
                    "home": "00 000000",
                    "office": "00 000000"
                }
        },
        .
        .
        .
        .
  ]
}

The difference between [ and { – (Square brackets and Curly brackets)

In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket ([) represents starting of an JSONArray node whereas curly bracket ({) represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.

If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.

json parsing structor

1. Creating New Project

So let’s start by creating a new android project. We’ll build a simple app which fetches the json from url, parses it and displays the contacts in a list view. Here we’ll use import java.net libraries (which are natively supported in android) to make the http call and fetch the json from url.

1. Create a new project in Android Studio from File ⇒ New Project and fill out the required details.

2. As we are fetching the JSON by making HTTP calls, we need to add INTERNET permission in AndroidManifest.xml file. Open AndroidManifest.xml and add the following permission.

<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.jsonparsing" >

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

3. Create a class named HttpHandler.java and use the below code. Here makeServiceCall() makes http call to particular url and fetches the response. In our case, we use this to get the raw json from the url.

package info.androidhive.jsonparsing;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Created by Ravi Tamada on 01/09/16.
 * www.androidhive.info
 */
public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

4. Before making the http call, let’s add a list view first in our view. Open the layout file of main activity (activity_main.xml) and add a ListView element.

<?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="info.androidhive.jsonparsing.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

5. Create another layout file named list_item.xml with following content. This will be used to render single list item view.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />

    <TextView
        android:id="@+id/mobile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />
</LinearLayout>

6. Open MainActivity.java and declare the necessary variables for the list view. If you haven’t worked with list view yet, Android ListView Tutorial will helps you in getting started.

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "https://api.androidhive.info/contacts/";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);
    }
}

1.1 Downloading & Parsing the JSON

7. As we are getting the JSON by making HTTP call, I am adding a Async class GetContacts to make http calls on background thread. Add the following method in your main activity class.

In onPreExecute() method progress dialog is shown before making the http call.

In doInBackground() method, makeServiceCall() is called to get the json from url. Once the json is fetched, it is parsed and each contact is added to array list.

In onPostExecute() method the progress dialog is dismissed and the array list data is displayed in list view using an adapter.

Also note that I have used getJSONArray() or getJSONObject() method depending on the type of node.

package info.androidhive.jsonparsing;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String TAG = MainActivity.class.getSimpleName();

    private ProgressDialog pDialog;
    private ListView lv;

    // URL to get contacts JSON
    private static String url = "https://api.androidhive.info/contacts/";

    ArrayList<HashMap<String, String>> contactList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contactList = new ArrayList<>();

        lv = (ListView) findViewById(R.id.list);

        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetContacts extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("contacts");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String id = c.getString("id");
                        String name = c.getString("name");
                        String email = c.getString("email");
                        String address = c.getString("address");
                        String gender = c.getString("gender");

                        // Phone node is JSON Object
                        JSONObject phone = c.getJSONObject("phone");
                        String mobile = phone.getString("mobile");
                        String home = phone.getString("home");
                        String office = phone.getString("office");

                        // tmp hash map for single contact
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("id", id);
                        contact.put("name", name);
                        contact.put("email", email);
                        contact.put("mobile", mobile);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"name", "email",
                    "mobile"}, new int[]{R.id.name,
                    R.id.email, R.id.mobile});

            lv.setAdapter(adapter);
        }

    }
}

If you run the project, you can see json data populated into list view as shown in the below image.

android json parsing tutorial

2. Json Parsing using Library

The above method is very easy for simpler json. If the json is very complex, it is better to consider the third party libraries as they are much faster and reliable. Below are the popular libraries used to parse the json.

2.1 Using Volley Library

Volley HTTP library provides easy way to make networks calls. In Android JSON parsing using Volley you can learn how to do that same in easy way using volley networking library which provides you lot of advantages like success/error callback methods and cache options.

2.2 Using Retrofit Library

Retrofit is much popular than volley. The parsing is done using jackson libraries in which you just have to create models for json nodes and the library automatically converts the json into appropriate objects. Go through Android Working with Retrofit HTTP Library which explains in detail about retrofit library.

Change Log

Updated On 27th Dec 2013 (Content Update, Bug fixes)
1st Sep 2016 (Content Update, Bug fixes, latest libraries)
Subscribe
Notify of
guest
213 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] of my previous tutorials. I hope you covered these tutorials before. Android making HTTP Requests Android JSON Parsing Tutorial Android SQLite Database Tutorial Android Login and Registration Screen […]

Mika Octo Frentzen
Mika Octo Frentzen
3 years ago

where i can put JSON Post in this Project?

Ravi Tamada
3 years ago

This is a beginner tutorial. Use Volley or Retrofit as mentioned at the bottom of the article.

Elena Smith
Elena Smith
3 years ago

How can you add a search functionality to this?

Ahmed El-Elaimy
Ahmed El-Elaimy
3 years ago

how can I parse Image not only text?

Ravi Tamada
3 years ago

Parsing image is getting the image url from the JSON. You have to use the url to display the image in a ImageView. Use Glide library to load the image.
https://www.androidhive.info/2016/04/android-glide-image-library-building-image-gallery-app/

Aishwary
Aishwary
3 years ago

it is showing an error as value of type java.lang.String can not be converted into JSON Object, when creating a JSON Object by passing the json string.

Kyle
Kyle
3 years ago

Nice guide! The url though needs to be changed to https as the site seams to auto-redirect from http

Ravi Tamada
3 years ago
Reply to  Kyle

I think url is updated to https already. Did I forgot to update it somewhere else?

Luisho
Luisho
3 years ago
Reply to  Ravi Tamada

In the MainActivity.java the http’s’ is missing. Thanks for the tutorial!

Ravi Tamada
3 years ago
Reply to  Luisho

Ok. Look into other advanced json parsing article mentioned at the bottom of the article.

Kyle
Kyle
3 years ago
Reply to  Ravi Tamada

In the MainActivity.java has this line:
private static String url = “http://api.androidhive.info/contacts/”;

Not a big deal, but might confuse some because if you load that link in a web browser it redirects to the https version.

Isma'il H.A. Ibn Thomas-Benge,
Isma'il H.A. Ibn Thomas-Benge,
3 years ago

Nice tutorial!
If I wanted to fetuses in put to change the url, how would I do that?
Example: if I wanted a editTextBox with a submit button: how could I make the user input into a variable and insert into the url string and return the Jason upon clicking the submit button using your code?

Ravi Tamada
3 years ago

You can’t do that directly without having some storage mechanism something like PHP / MySQL layer..

You need to learn about REST Api. Here are the couple of articles to get started

https://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

https://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-12-2/

Kunal
Kunal
3 years ago

How we do this from the fragment?

Ravi Tamada
3 years ago

Okay. The site is moved to https recently. I need to update all the articles.

jagan
jagan
3 years ago

Hi ravi, i went through your tutorials.all are good, pretty useful… i went on developing an android app [native app] for existing web app. the existing app is related to particular organisation. i went on implementing web service, but i am getting null response from the url, even connection is successful. in othercase if i hit the url in browser getting response.

could you please help me on this. also attached a file. Thanks

comment image

Remache Amine
Remache Amine
3 years ago

Hi I got this exception , could you help me ?comment image

Mehul Rana
Mehul Rana
3 years ago
Reply to  Remache Amine

hey….how did u solve this… ??

Ravi Tamada
3 years ago
Reply to  Mehul Rana

This will happen when json is not proper. It might have php or other errors printed in the response. Check for server logs or use Postman to see the php errors.

Ovalman
Ovalman
3 years ago
Reply to  Remache Amine

Hi Remache, change the web address in your MainActivity.java to https ie. “https://api.androidhive.info/contacts/”

Hi Ravi, great tutorial as always and I have it working but I’m wondering how we create the webpage like your https address so we can insert our own data? I’m looking to use free blogging software (blogger.com) if possible.

AngeL RodrigueZ
AngeL RodrigueZ
3 years ago

Hi super good explained !! I congratulate you!!!!
Already only one question will you have an example through POST ?? As a Login …

akash
akash
3 years ago

when i run this program i get error saying JSON parsing error value cannot be converted into JSONObject. what to do

AngeL RodrigueZ
AngeL RodrigueZ
3 years ago
Reply to  akash

Hi akash, change the web address in your MainActivity.java to https ie. “https://api.androidhive.inf…”

Basri Umar
Basri Umar
3 years ago

same as me, just view that image
how to solve?

Ravi Tamada
3 years ago

You need to buy a hosting and a web domain address. This article will give you some information.
https://www.androidhive.info/2015/03/android-hosting-php-mysql-restful-services-to-digitalocean/

Emin
Emin
3 years ago

Hello, good tutorial but i cant click listview or items of listview. I tried myListView.setOnItemClickListener(new AdapterView.OnItemClickListener(). Do you have any solution ?

Sanchi Bansal
Sanchi Bansal
3 years ago

I want to be able to click on an options menu item to change JSON data in ListView accordingly.
How do i do it?
How do I refresh my listview?

Ashutosh Choudhary
Ashutosh Choudhary
3 years ago

how to open an url, by passing it in json string, how to make it clickable in your above code.waiting for your response thankscomment image

Ashutosh Choudhary
Ashutosh Choudhary
3 years ago
Reply to  Ravi Tamada

thanks 🙂

Amir
Amir
3 years ago

hello

How to Parse JSON Show Images in upper example?

Chaimaa Elfa
Chaimaa Elfa
3 years ago

hello sir,
thank you for this helpfull tutorial its working for me,i have a question :
my JSON data contains images ,how can i parse it into a listview (like the upper example )?
thank you

Ravi Tamada
3 years ago
Reply to  Chaimaa Elfa

You can read this article.
https://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

(Be sure to replace ListView with RecyclerView once you understood)

Chaimaa Elfa
Chaimaa Elfa
3 years ago
Reply to  Ravi Tamada

the problem is that my json file contains a noud for images comment image

Chaimaa Elfa
Chaimaa Elfa
3 years ago
Reply to  Chaimaa Elfa

how can i put image in a listviewwith (using the json file mentionned upper)

Ikhsan
2 years ago
Reply to  Chaimaa Elfa

in List_item.xml you need to type the extension with id like this:

android:id=”@+id/imageView”
android:widht=”match_parent”
android:height=”wrap_content”

Ikhsan
2 years ago
Reply to  Chaimaa Elfa

You can try this,
when you create the text like this String id = c.getString(“id”);
you can replace by saying

String images = c.getImages(“images”) <– This Images you can type the images type on JSON file, like this

"images": "the link with .png extension in the end"

Swayam Singh
Swayam Singh
3 years ago

pls ravi sir tell me how to solve it.

E/HttpHandler: IOException: Unable to resolve host “api.androidhive.info”: No address associated with hostnam

E/MainActivity: Response from url: null

E/MainActivity: Couldn’t get json from server.

Ravi Tamada
3 years ago
Reply to  Swayam Singh

Is the device having internet connection? Also have you added INTERNET permission in manifest file?

Ravi Tamada
3 years ago

Can you post the error you are getting?

jay
jay
3 years ago
Reply to  Ravi Tamada

0)
{
// looping through all results
// products node

while ($row = mysql_fetch_array($result))
{
// temp user arrayId`, `Uname`, `Password`, `Aclocked`
array_push($res,array(
‘id’ => $row[“Id”],
‘uname’ => $row[“Uname”],
‘pass’ => $row[“Password”],
‘ac’ => $row[“Aclocked”]));

// push single product into final response array

}

// success

// echoing JSON response
echo json_encode($res);
}

?>

Ravi Tamada
3 years ago
Reply to  jay

Access the url in the browser. It has to echo proper json.

Chaimaa Elfa
Chaimaa Elfa
3 years ago

hi,
i need some help plz
i did the same thing mentionned in this tutorial ,now i want to display this information to another activity when one item from the listview is clicked
how can i do it ?

Ravi Tamada
3 years ago
Reply to  Chaimaa Elfa

You need to learn sending data between activities via Intents.

Refer this article
https://www.androidhive.info/2011/10/android-listview-tutorial/

Devesh Pandya
Devesh Pandya
3 years ago

i am getting at data of type org.json.JSONObject cannot be converted to JSONArray this error while passing my json. i have checked its a valid json format. can u plz help me out on this.

i found the solutions for this but didnt got any proper solution.

Ravi Tamada
3 years ago

Both json are different. Mine starts with an object, your’s is array. You need to parse accordingly.

Maker Labz
Maker Labz
2 years ago
Reply to  Ravi Tamada

In ma case its showing the Toast “Couldn’t get json from server. Check LogCat for possible errors….

Bindiya S
Bindiya S
3 years ago

hi, this code works fine..but it gives null for jsonstr if i use my own api url. application terminates at InputStream in = new BufferedInputStream(conn.getInputStream());
It will not proceed to the convertStreamToString(). why so? plz help me out.

Mehmet Balbay
Mehmet Balbay
3 years ago

Thank you for tutorial .

kapil
kapil
3 years ago

can you please tell me php code for this

Ravi Tamada
3 years ago
Reply to  kapil
kapil
kapil
3 years ago

comment image The data is not showing in listview. instead of listview it is showing on logcat. please help

Ravi Tamada
3 years ago
Reply to  kapil

Paste the code you have tried?

Ravi Tamada
3 years ago

You are parsing the JSON wrong. It starts with Array, but are parsing it as object. Using the same code for all the jsons won’t work. You need to understand the parsing correctly, use appropriately to your json.

kapil
kapil
3 years ago
Reply to  Ravi Tamada

can you suggest me how to pass json in my code

cheikhouna gueye
cheikhouna gueye
2 years ago

Hi i have this error i need your help

1-04 17:19:35.389 22965-22991/udemy.training.com.androidjsonparse E/MainActivity: Response from url:
301 Moved Permanently

301 Moved Permanently
nginx/1.10.3 (Ubuntu)

11-04 17:19:35.389 22965-22991/udemy.training.com.androidjsonparse E/MainActivity: Json parsing error: Value of type java.lang.String cannot be converted to JSONObject
11-04 17:19:35.489 22965-22965/udemy.training.com.androidjsonparse E/ViewRootImpl: sendUserActionEvent() mView == null

Ravi Tamada
2 years ago

The url is not providing the json. Open the url in browser and see.

cheikhouna gueye
cheikhouna gueye
2 years ago
Reply to  Ravi Tamada

Ok i see! It’s okay. I solved the problem. thank you

Ravi Tamada
2 years ago

You are welcome 🙂

Kashish Khurana
Kashish Khurana
2 years ago

How did u solve this problem?

Aditya
Aditya
2 years ago

I have downloaded your .apk file.
But I am getting error while running the app and the error is
Json parsing error: Value of type java.lang.String cannot be converted to JSONObject

Ravi Tamada
2 years ago
Reply to  Aditya

Which json url you are testing with? Seems json is not proper.

محمد اويس جميل
محمد اويس جميل
2 years ago

what if the array is look likecomment image

محمد اويس جميل
محمد اويس جميل
2 years ago

i solved the problem .i have to make just jason arry first .thanks man .your code is working perfectly

Ravi Tamada
2 years ago

Great.

cornelius kimutai
cornelius kimutai
2 years ago

What of Recylerview in place of Listview? How do I go about it?

Saqib Rauf
Saqib Rauf
2 years ago

Download apk provided in tutorial. But it display an error Value of type java.lang.String cannot be converted to JSONObject

Ravi Tamada
2 years ago
Reply to  Saqib Rauf

I see the problem. The site is recently moved to https, and the apk is still older (which points to http instead of https). I’ll upload the newer apk later.

Thanks for your notice.

Machhindra Sudke
Machhindra Sudke
2 years ago
Reply to  Ravi Tamada

i got same error.. i think your site not update from last 25days???

Dinesh
Dinesh
2 years ago

I want to print my Error from “onErrorResponse” using volley in android, i want to print them separately in different textview.

my error from onErrorResponse

{
“message”: “422 Unprocessable Entity”,
“error”: {

“username”: [
“The username has already been taken.”
],
“email”: [
“The email has already been taken.”
]
},
“status_code”: 422
}
so i want to print them separately, i mean “The username has already been taken.” in one textview and “The email has already been taken.” in 2nd textview. thank

Exynos SnapDragon
Exynos SnapDragon
2 years ago

I parsed 2 json sources into 2 separate arraylists using the method above.
List1: [{name=” ” ,count=” ” }]
List2: [{name=” ” ,change=” ” }].
I want to merge these 2 arraylists to form 1 arraylist with 3 fields like [{name=” ” ,count=” ” ,change=” ” }].
How can i do this? I tried
combined.addAll(List1)
combined.addAll(List2)
but the output only contains 2 fields, not the 3 fields that i would like.

Suhas Ar
Suhas Ar
2 years ago

Hello, thank you for the post,
here i have some issue in getting data by onclick event, i have got position by onClick and the entire data of the view that is: “{id=123, Age=25, sex=Male, address=House No.:18, guardianName=xyz, name=abc}”, but here i need each value separately like id,age,name etc. can you please help me out in this. tried lot many ways but am looking for best practice.

Thanks in advance.

Ban Midou
Ban Midou
2 years ago

nice tutorial , very easy to understand, by doing it 2-3 times i’ve learned it very well…….. thank you ravi ,
now going through volley library……

Ravi Tamada
2 years ago
Reply to  Ban Midou

Cool. After volley, learn Retrofit.

Ban Midou
Ban Midou
2 years ago
Reply to  Ravi Tamada

Yupp…….. ^_^

Forwa Elade
Forwa Elade
2 years ago

Hello Ravi,
Thanks very much for this tutorial,
I have been touring the web for days now and wasn’t still able to do this until i found your tutorial.
Thanks again once more and may the Almighty bless you in abundant.

Ravi Tamada
2 years ago
Reply to  Forwa Elade

You are welcome Forwa. Be sure to check the same json parsing using Volley and Retrofit.

Happy Coding 🙂

Machhindra Sudke
Machhindra Sudke
2 years ago

please check your wifi or network is on

Farrukh Saleem
Farrukh Saleem
2 years ago

Hello Sir Ravi Tamada.
i am using your tutorial it is fine but i have error when i run it
error is ” Json Parsing Error: no value for contact”

this is my code.
package info.androidhive.jsonparsing;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

// ArrayList ID = new ArrayList();
// ArrayList BarCode = new ArrayList();

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = “http://192.168.15.127:8198/api/Traffic/GetLicenceHolder/?strBarCode=123456”;

ArrayList<HashMap> EmployeeList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

EmployeeList = new ArrayList();

lv = (ListView) findViewById(R.id.list);

new GetContacts().execute();
}

/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask {

// @Override
// protected void onPreExecute() {
// super.onPreExecute();
// // Showing progress dialog
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage(“Please wait…”);
// pDialog.setCancelable(false);
// pDialog.show();
//
// }

@Override
protected Void doInBackground(Void… arg0) {
HttpHandler sh = new HttpHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);

Log.e(TAG, “Response from url: ” + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray(“contacts”);

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

String id = c.getString("ID");
String BarCode = c.getString("BarCode");
String E_name = c.getString("Employee Name");
String E_address = c.getString("Employee Address");
String E_email = c.getString("Employee Email");
String phonenmbr = c.getString("Employee PhoneNo.");
String status = c.getString("Status");

// String id = c.getString("id");
// String name = c.getString("name");
// String email = c.getString("email");
// String address = c.getString("address");
// String gender = c.getString("gender");

// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");

// tmp hash map for single contact
HashMap contact = new HashMap();

// adding each child node to HashMap key => value
contact.put(“ID”, id);
contact.put(“BarCode”, BarCode);
contact.put(“Employee Name”, E_name);
contact.put(“Employee Address”, E_address);
contact.put(“Employee Email”,E_email);
contact.put(“Employee PhoneNo.”,phonenmbr);
contact.put(“Status”,status);

// JSONObject id = c.getJSONObject(“ID”);
// String BarCode = BarCode.get

// adding contact to contact list
EmployeeList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, “Json parsing error: ” + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
“Json parsing error: ” + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});

}
} else {
Log.e(TAG, “Couldn’t get json from server.”);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
“Couldn’t get json from server. Check LogCat for possible errors!”,
Toast.LENGTH_LONG)
.show();
}
});

}

return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
// pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, EmployeeList,
R.layout.list_item, new String[]{“ID”, “BARCODE”,”EmployeeName”,”EmployeeAddress”,”EmployeeEmail”,”EmployeePhoneNo”,”Status”},
new int[]{R.id.id,R.id.BarCode, R.id.E_name,R.id.E_address,R.id.E_email,R.id.phonenmbr,R.id.status});

lv.setAdapter(adapter);
}

}
}

Ravi Tamada
2 years ago
Reply to  Farrukh Saleem

You need to make sure that the url you are accessing is returning valid json. You can hit the url from Postman and see.

Krishna Kumar
Krishna Kumar
2 years ago

Hello Ravi tamada
please post a tutorial or sample about quandl api. since its json is of complex

Ravi Tamada
2 years ago
Reply to  Krishna Kumar

Any sample of the json?

Aleks Kosyrev
Aleks Kosyrev
2 years ago

Good day to you Ravi!
Thanks a lot for this tutorial. Found this very usefull for my app, also found so much examples based on this code at stack))
Please let me know how to use code above to parce json to sqlite and then put it to listview. Spent two days to find appropriate solution.

Aleks Kosyrev
Aleks Kosyrev
2 years ago
Reply to  Ravi Tamada

Thanks!

Aleks Kosyrev
Aleks Kosyrev
2 years ago

Just faced with exeption “Json parsing error: Value null at percent_change_7d of type org.json.JSONObject$1 cannot be converted to int” How can I edit HttpHandler class to avoid it? Making String response = “”; instead of null not worked.

Ravi Tamada
2 years ago
Reply to  Aleks Kosyrev

Are you parsing the same response provided in the article?

Aleks Kosyrev
Aleks Kosyrev
2 years ago
Reply to  Ravi Tamada

No, error has dissapiared. Think problem was at server side

Ravi Tamada
2 years ago
Reply to  Aleks Kosyrev

Okay

emi
emi
2 years ago

JSON Parsing error value of type java.lang.string cannot be converted to JSONObject
The error shows after installing and running your app provided in this article. Can you solve it?

Ravi Tamada
2 years ago
Reply to  emi

Are you trying the below url? The json is loading properly.
https://api.androidhive.info/contacts/

If you are trying any other url, it is not responding with json. Instead it has some errors.

emi
emi
2 years ago
Reply to  Ravi Tamada

no im trying from the same url. Maybe the code it’s not working can you try to install the app?

Ravi Tamada
2 years ago
Reply to  emi

Are you trying the the url with https, not http?

emi
emi
2 years ago
Reply to  Ravi Tamada

I just download your apk from the source but it’s not working when i open the app

Ravi Tamada
2 years ago
Reply to  emi

Yeah probably the apk still pointing to http url.

Ravi Tamada
2 years ago

Hi Deependra

You can do this very easily.

1. First of all use RecyclerView to display the information in list. Don’t use the ListView. This article can help in displaying json data in list (ignore search part).
https://www.androidhive.info/2017/11/android-recyclerview-with-search-filter-functionality/

2. Second you need to find the item that is clicked. You can attach a click listener to RecyclerView and find the item index selected. Once index is known, you can get the item details from the ArrayList.
https://www.androidhive.info/2016/01/android-working-with-recycler-view/ You can learn RecyclerView and Click listener here.

3. Pass the selected item id or name (whatever parameter is required to get complete json of a single item). You can pass the data to another activity via intents.
https://www.androidhive.info/2011/08/how-to-switch-between-activities-in-android/ This article explains how to send data b/w activities via intents.

4. On the full details activity, get the item id sent from list activity and fetch the json by making http call again.

Deependra
Deependra
2 years ago
Reply to  Ravi Tamada

Thanks for help

emi
emi
2 years ago

Thanks for the tutorial i have a question how to make a onClickListener in order to open something when the user clicks on one of the contact names?

Ravi Tamada
2 years ago
Reply to  emi

Just write on click listener for your list view and pass the contact via intent to another activity.

emi
emi
2 years ago
Reply to  Ravi Tamada

can you provide me the source code ? I dont understand it sorry

emi
emi
2 years ago
Reply to  Ravi Tamada

can you write the code please????

Ravi Tamada
2 years ago

Could you post the code?

213
0
Would love your thoughts, please comment.x
()
x