Rapid Subscribe Android App

Rapid Subscribe Android App
Rapid Subscriber

Breaking News

Json Parsing to List View | Populate List View with Json Parsing in Android

Populate List View with Json Parsing in Android







In our Previous post, we have parsed json data and set values on a text view. We have fetch Json array single value and set it on a textview. We have fetch only single value from Json Array and set it on  a text view. 

In this post, we will fetch all json array values and populate it on  a list view. Also we create a Custom list view to set values on a list view.

  • Json Parsing in Android
  • Get Json Array values
  • Create a Custom xml layout with some textview to show array values
  • Http Handler class to handle Json data and parse it's objects and array.
  • Populate List view with all values.

JsonParsing.xml
 <?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"/>  
   <ListView  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_list_view"/>  
 </LinearLayout>  

Here, we create a text views, Button and a list view, we will populate listview on a button click. 
And also we will create a custom xml layout first to populate on list view.

Custom XML Layout
 <?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"  
   android:layout_margin="5dp">  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_id"  
     android:padding="3dp"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_name"  
     android:padding="3dp"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_year"  
     android:padding="3dp"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_color"  
     android:padding="3dp"/>  
   <TextView  
     android:layout_width="wrap_content"  
     android:layout_height="wrap_content"  
     android:id="@+id/json_pantone"  
     android:padding="3dp"/>  
 </LinearLayout>  

Http Handler.java to handle all http url json data.
 package studio.harpreet.sampleproject;  
 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();  
   }  
 }  

And in activity.java file, we will do all remaining work.
 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.ListAdapter;  
 import android.widget.ListView;  
 import android.widget.SimpleAdapter;  
 import android.widget.TextView;  
 import org.json.JSONArray;  
 import org.json.JSONObject;  
 import java.util.ArrayList;  
 import java.util.HashMap;  
 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;  
   ArrayList<HashMap<String, String>> list = new ArrayList<>();  
   ListView lv;  
   @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);  
     lv = findViewById(R.id.json_list_view);  
     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(i);//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  
             //There are more than one different strings, so change arraylist style.. to hashmap  
             HashMap<String,String> map = new HashMap();  
             //or you can add this  
             map.put("id","Id: "+id);  
             map.put("name","Name: "+name);  
             map.put("year","Year: "+year);  
             map.put("color","Color: "+color);  
             map.put("pantone","Pantone: "+pantone);  
             list.add(map);  
             //When the loop starts, automatically added all values in map and add map in list,  
             //again map clears and add values in map and added values in list.  
             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);*/  
       //Here we need to create a custom layout to see all the values differently..  
       ListAdapter adapter = new SimpleAdapter(Json_Parsing.this,list,R.layout.json_custom_layout,  
           new String[]{"id","name","year","color","pantone"},//use same id here, that you used in map, case sensitive  
           new int[]{R.id.json_id,R.id.json_name,R.id.json_year,R.id.json_color,R.id.json_pantone});  
       //use same path here, id for id, name for name  
       lv.setAdapter(adapter);  
       super.onPostExecute(aVoid);  
     }  
   }  
 }  



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

1 comment:

  1. รับทำ SEO ให้เว็บไซต์ของคุณติดอันดับที่ดี บนหน้าแรกของ google โดยทีมงานมืออาชีพ รับทำ seo

    ReplyDelete