Skip to main content

How to: JSON Data Fetching and Parsing Android Studio Tutorial in Java



Here is the Summary!

We will only be using one activity named MainActivity.java in this whole project.  This activity will be doing the data fetching as well as displaying that JSON data. For this, we will be declaring the MainActivity.java in the AndroidManifest.xml file. Look at the AndroidManifest.xml file below.

AndroidManifest.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.abhishekpanwar.receivedatajson">
  
  <uses-permission android:name="android.permission.INTERNET"/>
  
  <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" 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>

Fetching the JSON data.

For this purpose, we will be declaring a class named
fetchData.java which will be extending from AsyncTask. AsyncTask is used for simple
asynchronous jobs like fetching data from a webserver etc. 

Asynchronous jobs are the jobs about which we don't know when it will be done executing, for example, we don't know here how much time it will take to fetch the JSON data as it depends on the internet speed, data size etc.

Hence we can't run asynchronous jobs in the main thread or else the UI of the app will be blocked. So we use AsyncTask to run these types of jobs in a different thread. Look at the fetchData.java file below which extends from AsyncTask.

fetchData.java
package com.abhishekpanwar.receivedatajson;

import android.os.AsyncTask;

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

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.URL;

/**
 * Created by Abhishek Panwar on 7/14/2017.
 */

public class fetchData extends AsyncTask {
    String data ="";
    String dataParsed = "";
    String singleParsed ="";
    @Override
    protected Void doInBackground(Void... voids) {
        try {
            URL url = new URL("https://api.myjson.com/bins/j5f6b");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray JA = new JSONArray(data);
            for(int i =0 ;i < JA.length(); i++){
                JSONObject JO = (JSONObject) JA.get(i);
                singleParsed =  "Name:" + JO.get("name") + "\n"+
                                "Password:" + JO.get("password") + "\n"+
                                "Contact:" + JO.get("contact") + "\n"+
                                "Country:" + JO.get("country") + "\n";

                dataParsed = dataParsed + singleParsed +"\n" ;


            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        MainActivity.data.setText(this.dataParsed);

    }
}

We are doing the JSON data fetching job in the doInBackground() method. Once the JSON data is completely fetched, onPostExecute() method is called. Now in the onPostExecute method we are setting the content of the Textview in the MainActivity.java equal to the fetched JSON data.

In the MainActivity.java we will be starting the JSON data fetching process when a Button is
clicked. For this, we set up an OnClickListener to the Button.

MainActivity.java
package com.abhishekpanwar.receivedatajson;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button click;
    public  static TextView data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        click = (Button) findViewById(R.id.button);
        data = (TextView) findViewById(R.id.fetcheddata);

        click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                  fetchData process = new fetchData();
                  process.execute();
            }
        });

    }
}

Thus, we learned how to fetch and parse JSON data in Android using AsyncTask. Subscribe to the newsletter for more such amazing content. Also visit codebrink.org for latest posts on coding.

Find the Source Code here: JSON Data Fetching Android Project



Comments

  1. There is an error of json. TypeMismatch
    How to resolve it???

    ReplyDelete
    Replies
    1. https://www.google.com/search?q=Unknown+23+July+2018+at+01:42+There+is+an+error+of+json.+TypeMismatch+How+to+resolve+it???&spell=1&sa=X&ved=0ahUKEwi0mY-OwqLkAhXb7XMBHU70DMMQBQguKAA&biw=1920&bih=969

      Delete
  2. What about for complext multilevel JSONarray Sir

    ReplyDelete
  3. Abby! Keep up the great work ..

    ReplyDelete
  4. error on asynctask arugments ,,,,,
    how to resolve it

    ReplyDelete
  5. i need help i have url i want to just perform action on button by clicking on button. not opening that url just click

    ReplyDelete
  6. {
    "Username": "sample string 1",
    "Password": "sample string 2",
    "UserPIN": "sample string 3",
    "DeviceMACID": "sample string 4",
    "DeviceIP": "sample string 5",
    "PublicIP": "sample string 6",
    "Latitude": "sample string 7",
    "Longitude": "sample string 8"
    }

    how to post this data and how to retrave response

    ReplyDelete
  7. How to filter data.
    for Example .
    I only want to show the people who lives only india.

    ReplyDelete
  8. where we use NotifyDataSetChanged() if we using RecyclerView in when we Fetching Data from Json..?
    Thanks in Advance.

    ReplyDelete
  9. How would I retrieve data if the json file has an object within an object so for example.
    {
    "id":1,
    "name":"bret",
    "address": {
    "street":"streetname"
    "city":"city name"
    }
    }

    ReplyDelete
  10. {
    "Sheet1":[
    {"Phone_Number":9638527410},
    {"Phone_Number":7418529630},
    {"Phone_Number":7539510005},
    {"Phone_Number":9876543210},
    {"Phone_Number":7894561230}]
    }

    How to retrieve this data

    ReplyDelete
  11. how to ue json api in listview in android

    ReplyDelete
  12. thanks for sharing good article. visit one more json java tutorials

    ReplyDelete
  13. Thank You so much for your effort in sharing such a wonderful blog with us.

    This is good information and really helpful for the people who need information about this. Good information. Thanks for sharing with us Igained more knowledge from your blog. Keep Doing..
    oracle training in chennai

    oracle training institute in chennai

    oracle training in bangalore

    oracle training in hyderabad

    oracle training

    hadoop training in chennai

    hadoop training in bangalore


    ReplyDelete

Post a Comment

Popular posts from this blog

How to create a one time Splash Screen in Android Studio. Android tutorials for beginners.

SplashScreen.java import android.content.Intent; import android.content.SharedPreferences; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class SplashScreen extends AppCompatActivity { SharedPreferences sharedPreferences; Boolean firstTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); sharedPreferences = getSharedPreferences("MyPrefs",MODE_PRIVATE); firstTime = sharedPreferences.getBoolean("firstTime",true); if (firstTime){ new Handler().postDelayed(new Runnable() { @Override public void run() { SharedPreferences.Editor editor = sharedPreferences.edit(); firstTime = false; editor.putBoolean("firstTime",