Android populate listview from json using volley

Volley is a well-optimized library for networking. It focuses on simplicity and speed. Volley runs a network related task in a separated thread. So, you do not need AsyncTask anymore. Before using Volley, I used AsyncTask to access network resources on a remote server. It works fine. After using Volley, I recognize that it is more simple and faster than AsyncTask. However, Google recommends that you use the Volley to access small online resources. It should not be used to upload or download large files.
To use the Volley library in your project, you download volley.jar file from The Central Repository and place it in the libs directory of your project. In Android Studio, right-click the volley.jar and select Add As Library.
Now let’s create an example that uses Volley to get json array from the following address: http://www.gtwebsolutions.net/kent/getoutlet.php.
Here is the json array that returns from the above address. We are going to extract owner_name field from the json array.




json data

Open the activity_main.xml file and add a ListView.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    android:padding="10dp"    tools:context=".MainActivity"   > <ListView    android:id="@+id/listv"    android:layout_width="match_parent"    android:layout_height="wrap_content">    </ListView> </LinearLayout>


In the layout directory, you create item_layout.xml file to be used as an item template of the ListView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical" android:layout_width="match_parent"
   android:layout_height="match_parent">
   <TextView
      android:id="@+id/txt"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      >
   </TextView>
</LinearLayout>


In the MainActivity class, you write code to make a request to get json array from "http://www.gtwebsolutions.net/kent/getoutlet.php" address, parse it, and display the result in the ListView. First, you have to create an instance of RequestQueue class using newInstance() method of the Volley class. Then you create an instance of JsonArrayRequest. You pass to constructor of JsonArrayRequest an request method (GET or POST), an address or url of a file on remote server, an object of Listener to handle the successful response, and an object of ErrorListener to hander unsuccessful response. Finally, you add the json array request to the request queue using add() method.

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends ActionBarActivity {      ArrayAdapter<String> adapter;      ArrayList<String> items;      protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        ListView listView=(ListView)findViewById(R.id.listv);        items=new ArrayList<String>();        adapter=new ArrayAdapter(this, R.layout.item_layout,R.id.txt,items);        listView.setAdapter(adapter);
     }
   public void onStart(){      super.onStart();      // Create request queue      RequestQueue requestQueue= Volley.newRequestQueue(this);      // Create json array request      JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST,"http://www.gtwebsolutions.net/kent/getoutlet.php",new Response.Listener<JSONArray>(){
        public void onResponse(JSONArray jsonArray){
           // Successfully download json
           // So parse it and populate the listview           for(int i=0;i<jsonArray.length();i++){
             try {
                JSONObject jsonObject=jsonArray.getJSONObject(i);                items.add(jsonObject.getString("owner_name"));
             } catch (JSONException e) {
                e.printStackTrace();
             }
           }            adapter.notifyDataSetChanged();
        }
     }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
           Log.e("Error", "Unable to parse json array");
        }
     });
     // add json array request to the request queue
     requestQueue.add(jsonArrayRequest);
   } }


json volley

Posted by: Dara | post date: 05-31-2015 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.