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.
There is an error of json. TypeMismatch
ReplyDeleteHow to resolve it???
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
DeleteWhat about for complext multilevel JSONarray Sir
ReplyDeleteAbby! Keep up the great work ..
ReplyDeleteNice let me execut it
ReplyDeleteerror on asynctask arugments ,,,,,
ReplyDeletehow to resolve it
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{
ReplyDelete"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
How to filter data.
ReplyDeletefor Example .
I only want to show the people who lives only india.
where we use NotifyDataSetChanged() if we using RecyclerView in when we Fetching Data from Json..?
ReplyDeleteThanks in Advance.
How would I retrieve data if the json file has an object within an object so for example.
ReplyDelete{
"id":1,
"name":"bret",
"address": {
"street":"streetname"
"city":"city name"
}
}
{
ReplyDelete"Sheet1":[
{"Phone_Number":9638527410},
{"Phone_Number":7418529630},
{"Phone_Number":7539510005},
{"Phone_Number":9876543210},
{"Phone_Number":7894561230}]
}
How to retrieve this data
how to ue json api in listview in android
ReplyDeleteGreat blog !! thanks for sharing the Valuable information
ReplyDeleteMean stack online training
Mean stack training in hyderabad
excellent...!!!
ReplyDeleteSelenium training in chennai
Industrial visit in chennai
Internship
Internships in bangalore for cse students 2019
Free internship in chennai for cse students
Network security projects for cse
Ccna course in chennai
Inplant training in chennai for cse
Inplant training for eee students
Kaashiv infotech chennai
thanks for sharing good article. visit one more json java tutorials
ReplyDeleteThank You so much for your effort in sharing such a wonderful blog with us.
ReplyDeleteThis 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
https://globexdocuments.co//
ReplyDeletehttps://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
ReplyDeletehttps://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//
https://globexdocuments.co//