How to parse JSON using Volley Network library and receive JSON response from server and populate ListView items one by one from received response.
Volley makes our work more convenient because using volley we can write a little amount of code and that works like a full code. So in this tutorial we would going to create a fully customized JSON Parsing ListView using volley library. The JSON is arrived from MySQL database using PHP script. That means PHP is transforming MySQL data into JSON data.
What we are doing in this project : In this tutorial we would going to crate a ListView with multiple items inside it using Volley library. The ListView is fully customized and user can modify its each element style. Each row contains two type of data. First is Subject ID and second is Subject Name.
Project description :
Activity in this project :
- MainActivity.java
Java Files in this project :
- ListAdapter.java
- Subject.java
Layout files in this project :
- activity_main.xml
- listview_items.xml
Contents in this project Android Volley Custom JSON parsing ListView :
1. Create a database on your hosting server.
2. Create a new table in your database. The table has two columns, id and stubject_Name . Now enter some records like i did in below example.
3. Create PHP script to transform the MySQL data into JSON :
Code for DatabaseConfig.php file.
<?php //Define your host here. $HostName = "localhost"; //Define your database username here. $HostUser = "id302300_android_examples_data_user"; //Define your database password here. $HostPass = "1234567890"; //Define your database name here. $DatabaseName = "id302300_android_examples"; ?>
Code for user_login.php file.
<?php include 'DatabaseConfig.php'; // Create connection $conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM SubjectsTable"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $tem = $row; $json = json_encode($tem); } } else { echo "No Results Found."; } echo $json; $conn->close(); ?>
5. Start a new android application development project.
6. Add internet permission in AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>
7. Add compile ‘com.android.volley:volley:1.0.0’ library file in build.gradle(Module:app) file. So open it.
8. Add compile ‘com.android.volley:volley:1.0.0’ inside dependencies block.
9. Add ListView, ProgressBar and Button in activity_main.xml .
<ListView android:layout_width="fill_parent" android:layout_height="400dp" android:id="@+id/listView1" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_above="@+id/button"> </ListView> <ProgressBar android:id="@+id/ProgressBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:visibility="gone" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="LOAD JSON FROM SERVER" android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" />
10. Add ListView, Button, String to hold Http Url, String to hold complete JSON response and Progress bar object in MainActivity .
ListView listView; Button button; // Server Http URL String HTTP_URL = "https://android-examples.000webhostapp.com/all_subjects.php"; // String to hold complete JSON response object. String FinalJSonObject ; ProgressBar progressBar;
11. Assign ID’S to them.
// Assign ID's to ListView. listView = (ListView) findViewById(R.id.listView1); button = (Button)findViewById(R.id.button); progressBar = (ProgressBar)findViewById(R.id.ProgressBar1);
12. Add click listener to button.
// Adding click listener to button. button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } });
13. Create a new class named as ListViewAdapter.java .
package com.android_examples.volleyjsonlistview_android_examplescom; /** * Created by Juned on 6/17/2017. */ import java.util.List; import android.app.Activity; import android.view.View; import android.widget.TextView; import android.content.Context; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.view.LayoutInflater; public class ListViewAdapter extends BaseAdapter { Context context; List<Subject> TempSubjectList; public ListViewAdapter(List<Subject> listValue, Context context) { this.context = context; this.TempSubjectList = listValue; } @Override public int getCount() { return this.TempSubjectList.size(); } @Override public Object getItem(int position) { return this.TempSubjectList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewItem viewItem = null; if(convertView == null) { viewItem = new ViewItem(); LayoutInflater layoutInfiater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); convertView = layoutInfiater.inflate(R.layout.listview_items, null); viewItem.IdTextView = (TextView)convertView.findViewById(R.id.textviewID); viewItem.NameTextView = (TextView)convertView.findViewById(R.id.textviewSubjectName); convertView.setTag(viewItem); } else { viewItem = (ViewItem) convertView.getTag(); } viewItem.IdTextView.setText(TempSubjectList.get(position).Subject_ID); viewItem.NameTextView.setText(TempSubjectList.get(position).Subject_Name); return convertView; } } class ViewItem { TextView IdTextView; TextView NameTextView; }
14. Create another class named as Subject.java .
package com.android_examples.volleyjsonlistview_android_examplescom; /** * Created by Juned on 6/17/2017. */ public class Subject { public String Subject_ID; public String Subject_Name; }
15. Create another layout file named as listview_items.
In this calls we have define the individual textview elements for list view. You can customize this layout according to your requirement.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text1" android:text="Subject ID = " android:textSize="22dp" android:textColor="#000" android:layout_marginTop="10dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/textviewID" android:text="ID Show Here" android:textSize="22dp" android:textColor="#000" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/text1" android:layout_toEndOf="@+id/text1" android:layout_marginTop="10dp"/> <TextView android:id="@+id/textviewSubjectName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Subject Name Show Here" android:textColor="#2196F3" android:textSize="20dp" android:layout_below="@+id/textviewID" android:layout_marginTop="10dp"/> </RelativeLayout>
16. Create and call StringRequest and RequestQueue object inside your button scope. This method will return the whole JSON as a object in string variable.
// Adding click listener to button. button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Showing progress bar just after button click. progressBar.setVisibility(View.VISIBLE); // Creating StringRequest and set the JSON server URL in here. StringRequest stringRequest = new StringRequest(HTTP_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { // After done Loading store JSON response in FinalJSonObject string variable. FinalJSonObject = response ; // Calling method to parse JSON object. new ParseJSonDataClass(MainActivity.this).execute(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Showing error message if something goes wrong. Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show(); } }); // Creating String Request Object. RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this); // Passing String request into RequestQueue. requestQueue.add(stringRequest); } });
17. Create another calls in your MainActivity named as ParseJSonDataClass and extends AsyncTask in this class.
// Creating method to parse JSON object. private class ParseJSonDataClass extends AsyncTask<Void, Void, Void> { public Context context; // Creating List of Subject class. List<Subject> CustomSubjectNamesList; public ParseJSonDataClass(Context context) { this.context = context; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... arg0) { try { // Checking whether FinalJSonObject is not equals to null. if (FinalJSonObject != null) { // Creating and setting up JSON array as null. JSONArray jsonArray = null; try { // Adding JSON response object into JSON array. jsonArray = new JSONArray(FinalJSonObject); // Creating JSON Object. JSONObject jsonObject; // Creating Subject class object. Subject subject; // Defining CustomSubjectNamesList AS Array List. CustomSubjectNamesList = new ArrayList<Subject>(); for (int i = 0; i < jsonArray.length(); i++) { subject = new Subject(); jsonObject = jsonArray.getJSONObject(i); //Storing ID into subject list. subject.Subject_ID = jsonObject.getString("id"); //Storing Subject name in subject list. subject.Subject_Name = jsonObject.getString("subject_Name"); // Adding subject list object into CustomSubjectNamesList. CustomSubjectNamesList.add(subject); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { // After all done loading set complete CustomSubjectNamesList with application context to ListView adapter. ListViewAdapter adapter = new ListViewAdapter(CustomSubjectNamesList, context); // Setting up all data into ListView. listView.setAdapter(adapter); // Hiding progress bar after all JSON loading done. progressBar.setVisibility(View.GONE); } }
Complete source code for Volley Custom JSON parsing ListView :
Code for MainActivity.java file.