
In this post I will show you how to Parse JSON in Android. This tutorial is for absolute beginners. Parse JSON or Parsing JSON helps us to retrieve data from Online Database to our Android app. So lets see how to Parse JSON in Android
What is JSON?
- JSON stands for JavaScript Object Notation.
- In JSON information is stored in an organised and easy to access manner so it is easily readable and understandable by humans.
Example:
- Above shown is the format of JSON.
- All the variables are stored in key and value pair for ex, from the above data “age” is key and “27” is a value.
- By enclosing the variable’s value in curly braces, we’re indicating that the value is an object i.e data inside {} is object.
- In the above data [ ] indicates an array.All the objects are stored with in an array.
- we can access JSON data using an URL.In below example I am going to use this link “http://www.i2ce.in/reviews/1/1”.
How this program works:
- Initially we call AsyncTask from mainactivity.java with in that(asynctask) we establish a connection to communicate with the server.
- Server will send the JSON data back to the Asynctask in mainactivity that data is stored temporarily in ratings.java by creating new objects for each rating.
- JSON data will be received by adapter by get method in Ratings.java and pass this data to the listview.
- And our final listview will be like as shown in above image’s UI layout.
parsing JSON data:
step-1:
we have to add internet access permission in our manifest file.
1 |
<uses-permission android:name="android.permission.INTERNET"/> |
step-2:
(use this step only if you get any errors while importing http libraries )
Add below line to gradle file after default configuration.
1 2 3 |
android { useLibrary 'org.apache.http.legacy' } |
Add below dependencies into dependencies at the end of the gradle file.
1 2 |
compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5' |
finally your gradle file should look like this.
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 |
apply plugin: 'com.android.application' android { compileSdkVersion 24 buildToolsVersion "24.0.0" defaultConfig { applicationId "com.some.yrate" minSdkVersion 15 targetSdkVersion 24 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } android { useLibrary 'org.apache.http.legacy' } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:24.2.1' testCompile 'junit:junit:4.12' compile 'org.apache.httpcomponents:httpcore:4.4.1' compile 'org.apache.httpcomponents:httpclient:4.5' } |
step-3:
we have to add a listview in activity_main.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" 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" > <ListView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/list_item" /> </LinearLayout> |
step-4:
we have to create a layout contains some list of items which are display in activity-main’s listview.
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 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#166CED" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/comment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#D64530" /> <TextView android:id="@+id/usefulness" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#D64530" android:textAppearance="?android:attr/textAppearanceSmall" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="20dp" android:text="overall rating" android:textColor="#D64530"/> <RatingBar android:layout_width="wrap_content" android:layout_height="40dp" android:numStars="5" android:stepSize="1" android:id="@+id/ratingbar"/> </LinearLayout> </LinearLayout> |
step-5:
create a java class called reviews, declare required variables . create getters and setters for those variables as shown below.
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 |
public class reviews { String title,comment,usefulness,stars; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getUsefulness() { return usefulness; } public void setUsefulness(String usefulness) { this.usefulness = usefulness; } public String getStars() { return stars; } public void setStars(String stars) { this.stars = stars; } } |
step-6:
create reviewsadapter.java class and add below code into that
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 |
public class reviewsadapter extends ArrayAdapter<reviews> { private ArrayList<reviews> reviewList; private LayoutInflater vi; private int Resource; private ViewHolder holder; // Button soww; View view; //ArrayList<Reviews> cp=0; int gen=0; reviewsadapter(Context context, int resource, ArrayList<reviews> objects) { super(context, resource, objects); vi = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); Resource = resource; this.reviewList = objects; } @Override public View getView(int position, View convertView, @NonNull ViewGroup parent) { View v = convertView; // if view is null then set below views if (v == null) { holder = new ViewHolder(); v = vi.inflate(Resource, null); //binding holder variables to xml views holder.tvtitle = (TextView) v.findViewById(R.id.title); holder.tvcomment = (TextView) v.findViewById(R.id.comment); holder.tvusefullness = (TextView) v.findViewById(R.id.usefulness); holder.rbrating = (RatingBar) v.findViewById(R.id.ratingbar); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } //setting data to the holder vars from "Reviews" getters holder.tvtitle.setText(reviewList.get(position).getTitle()); holder.tvcomment.setText(reviewList.get(position).getComment()); holder.tvusefullness.setText("usefullness:"+reviewList.get(position).getUsefulness()); holder.rbrating.setRating(Integer.parseInt(reviewList.get(position).getStars())); return v; } private static class ViewHolder { TextView tvtitle; TextView tvcomment; TextView tvusefullness; RatingBar rbrating; } } |
step-7:
open MainActivity.java and add below code.
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 |
public class MainActivity extends AppCompatActivity { ArrayList<reviews> reviewList; reviewsadapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); reviewList = new ArrayList<reviews>(); new JSONAsyncTask().execute("http://www.i2ce.in/reviews/1/1"); final ListView listview = (ListView) findViewById(R.id.list_item); adapter = new reviewsadapter(getApplicationContext(), R.layout.row, reviewList); listview.setAdapter(adapter); } class JSONAsyncTask extends AsyncTask<String, Void, Boolean> { private ProgressDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); //for displaying progress bar dialog = new ProgressDialog(MainActivity.this); dialog.setMessage("Loading, please wait"); dialog.setTitle("Connecting server"); dialog.show(); dialog.setCancelable(false); } @Override protected Boolean doInBackground(String... urls) { try { //establishing http connection //------------------>> HttpGet httppost = new HttpGet(urls[0]); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httppost); // StatusLine stat = response.getStatusLine(); int status = response.getStatusLine().getStatusCode(); // if connected then access data if (status == 200) { HttpEntity entity = response.getEntity(); String data = EntityUtils.toString(entity); JSONObject jsono = new JSONObject(data); JSONArray jarray = jsono.getJSONArray("reviews"); for (int i = 0; i < jarray.length(); i++) { JSONObject object = jarray.getJSONObject(i); reviews rev = new reviews(); //getting json object values from json array rev.setTitle(object.getString("title")); rev.setComment(object.getString("comment")); rev.setUsefulness(object.getString("usefulness")); //getting value within json object JSONObject numstar = object.optJSONObject("ratings"); String sta = numstar.getString("Overall"); rev.setStars(sta); //adding data to the arraylist reviewList.add(rev); } return true; } //------------------>> } catch (ParseException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } return false; } protected void onPostExecute(Boolean result) { // if data dint fetch from the url dialog.cancel(); adapter.notifyDataSetChanged(); if (result == false) Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show(); } } } |
Finally output should look like this:
Download source code below:
[ihc-hide-content ihc_mb_type=”show” ihc_mb_who=”reg” ihc_mb_template=”1″ ]Download[/ihc-hide-content]