Rapid Subscribe Android App

Rapid Subscribe Android App
Rapid Subscriber

Recent Posts

Json Parsing in Android

Json Parsing in Android


JSon parsing is a short form for Java Script Object Notation. It is used to parse online http Json data.
Json data is in the form of objects (starts with { } braces) and arrays (starts with [ ]).

We use Json Parsing to handle Json data from Server Api and set it in our Android App or Website According to our design layout or choice..




In This post we use Json parsing and fetch some data from there. 

We use a Json url from an Api for testing purposes, you can use any url if you know how to get that Json Values. 

Json Url
 https://reqres.in/api/products/  

So, Create an Android Project and open it.

To use Json Parsing in Android, We will create a Httphandler class to handle http data and fetch values from their.

httphandler.java
 import android.util.Log;  
 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;  
 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();  
   }  
 }  

With this class we will handle and fetch all data from http url and use in our app

After that we have created 
  • Two textviews (1 for fetched object values and 2nd for fetched array values) to set fetched values on it. 
  • Button to execute async method.
  • Edittext to get position value of array.
XML Code
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   xmlns:app="http://schemas.android.com/apk/res-auto"  
   xmlns:tools="http://schemas.android.com/tools"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical"  
   android:layout_margin="10dp"  
   tools:context=".Json_Parsing">  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/et"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:textSize="16sp"  
     android:maxLines="7"  
     android:id="@+id/tv1"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:maxLines="7"  
     android:textSize="16sp"  
     android:id="@+id/tv2"/>  
   <Button  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:text="Get Data"  
     android:id="@+id/getbtn"/>  
 </LinearLayout>  

After that in Java Code, We will create an Async Task class to execute that http handler class to fetch values from http json url.

Java Code
 package studio.harpreet.sampleproject;  
 import androidx.appcompat.app.AppCompatActivity;  
 import android.os.AsyncTask;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.View;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.TextView;  
 import org.json.JSONArray;  
 import org.json.JSONObject;  
 public class Json_Parsing extends AppCompatActivity {  
   String Json_string = "https://reqres.in/api/products/";  
   String objectsvalue = "",arrayvalue = ""; // objectvalue for combining some string and set on textview ,  
                         // arrayvalue string to get value and show it on textview  
   EditText et;  
   TextView tv1,tv2;  
   Button btn;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_json__parsing);  
     et = findViewById(R.id.et);  
     tv1 = findViewById(R.id.tv1);  
     tv2 = findViewById(R.id.tv2);  
     btn = findViewById(R.id.getbtn);  
     btn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         new GetData().execute();  
       }  
     });  
   }  
   private class GetData extends AsyncTask<Void,Void,Void>  
   {  
     @Override  
     protected void onPreExecute() {  
       super.onPreExecute();  
     }  
     @Override  
     protected Void doInBackground(Void... voids) {  
       HttpHandler hh = new HttpHandler();  
       String jsonstr = hh.makeServiceCall(Json_string);  
       Log.e("TAG", "doInBackground: response from url "+jsonstr );  
       try {  
         if (jsonstr != null)  
         {  
           JSONObject jsonObject = new JSONObject(jsonstr); //because it starts from object class  
           String per_page = jsonObject.getString("per_page");  
            String total = jsonObject.getString("total");  
            String url = jsonObject.getJSONObject("support").getString("url");  
            String text = jsonObject.getJSONObject("support").getString("text");  
           objectsvalue = "per_page: "+per_page+"\n"  
               +"total: " +total+"\n"  
               +"url: "+ url +"\n"  
               +"text: "+ text;  
           JSONArray data_array = jsonObject.getJSONArray("data");  
           for(int i = 0; i < data_array.length(); i++)  
           {  
             JSONObject obj = data_array.getJSONObject(Integer.parseInt(et.getText().toString()));//sets to custom position  
                                                       // i is your position  
             String id = obj.getString("id");  
             String name = obj.getString("name");  
             String year = obj.getString("year");  
             String color = obj.getString("color");  
             String pantone = obj.getString("pantone_value"); //all values are case-sensitive, must be same  
             arrayvalue = "id: "+id+"\n"+  
                 "name: "+name+"\n"  
                 +"year: "+year+"\n"  
                 +"color: "+color+"\n"  
                 +"pantone: "+pantone; // we have store value in a string variable. we can't set a value to textview from here  
                             // we can only set a value from onpostexecute method.  
                           // it's a process of do in background , on pre execute then do in background then  
                         // on post execute  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         Log.e("TAG", "doInBackground: "+e.getMessage() );  
       }  
       return null;  
     }  
     @Override  
     protected void onPostExecute(Void aVoid) {  
       tv1.setText(arrayvalue);  
       tv2.setText(objectsvalue);  
       super.onPostExecute(aVoid);  
     }  
   }  
 }  

Now, In Java Code, we have fetch all values with json object and json arrays. and set it on textviews by concat all string values.


Follow us for more posts like this, 
Subscribe to Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

No comments