Android

Android JSON Parsing Using Volley

android json parsing using volley
Written by Yasir Ameen

Most of the time we need to fetch information from other source and then parse it to make it use in our application. Information can be of different formats like XML, JSON, Atom and other format. I am going to use JSON data in this tutorial.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

Let’s Start JSON Parsing Using Volley

I tried to simplify the meaning of JSON Parsing using the image below.

Android Json ParsingStep A- Create Project With Empty Activity

step-1) Open Android Studio  and create a project with empty Activity, and name in it  JSON Parsing.

Important :

<uses-permission android:name="android.permission.INTERNET"/>

Volley

I am using volley library in JSON Parsing project. Volley is Networking library which deals HTTP request very easily with fast performance. You can include volley library in your project by adding the following dependencies.

dependencies {
   
    compile 'com.android.volley:volley:1.0.0'
}

step-2) Create new layout resource file in your project and name it list_item_templates.xml , this xml is used for the template of list items of ListView. Result of list_item_templates.xml should look like below

 

JSON Parsing

 

step-3) Open list_item_templates.xml and paste the following xml.


<?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">

    <ImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_marginLeft="12dp"
        android:layout_marginTop="14dp"

        android:id="@+id/gameImage"
        android:paddingBottom="10dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Devil May Cry"
        android:textSize="18sp"
        android:id="@+id/tvtitle"
        android:paddingLeft="4dp"
        android:paddingRight="5dp"
        android:layout_alignTop="@+id/gameImage"
        android:layout_toRightOf="@+id/gameImage"
        android:layout_toEndOf="@+id/gameImage" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:lines="1"
        android:ellipsize="end"
        android:paddingLeft="4dp"
        android:paddingRight="5dp"
        android:textSize="12sp"
        android:id="@+id/tvdesc"
        android:layout_below="@+id/tvtitle"
        android:layout_alignLeft="@+id/tvtitle"
        android:layout_alignStart="@+id/tvtitle"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmallPopupMenu"
        android:text="Plateform : PS3, XBOX 360"
        android:id="@+id/tvplateform"
        android:paddingLeft="4dp"
        android:paddingRight="5dp"
        android:paddingBottom="5dp"
        android:textSize="12sp"
        android:layout_below="@+id/tvdesc"
        android:layout_alignLeft="@+id/tvdesc"
        android:layout_alignStart="@+id/tvdesc" />

</RelativeLayout>

 

Result of list_item_templates.xml should look like this.

Json Parsing

 

 

step-4) Open activity_main.xml and paste the following xml code.

This is activiy_main.xml file which will be used to display our JSON data in a listview.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context="com.yasirameen.jsonparsing.MainActivity">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

   </RelativeLayout>

 

Step B- Writing a Games Class [POJO]

Create a class Games.java in your project . This is the POJO [Plain Old Java Objects] class for model our JSON data we fetch from the network. In our JSON, we have data with following fields so we need to model the data according the json fields, we will use this class in JSON Parsing

JSON

Now open Games.java and paste the following code.


Games.java

public class Games {

    private String id;
    private String title;
    private String desc;
    private String platforms;
    private String image;
    private Bitmap bitmap;

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getPlatforms() {
        return platforms;
    }

    public void setPlatforms(String platforms) {
        this.platforms = platforms;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public Bitmap getBitmap() {
        return bitmap;
    }

    public void setBitmap(Bitmap bitmap) {
        this.bitmap = bitmap;
    }
}

 

Step C- Writing a Parser Class For JSON Data.

Create a class GamesJSONParser.java and write the following code. This is our parser class, this class help us to parse JSON data into our model class Games.java.


GamesJSONParser

public class GamesJSONParser {

    static List<Games> gamesList;

    public static List<Games> parseData(String content) {

        JSONArray games_arry = null;
        Games games = null;
        try {

            games_arry = new JSONArray(content);
            gamesList = new ArrayList<>();

            for (int i = 0; i < games_arry.length(); i++) {

                JSONObject obj = games_arry.getJSONObject(i);
                games = new Games();

                games.setId(obj.getString("id"));
                games.setTitle(obj.getString("title"));
                games.setDesc(obj.getString("desc"));
                games.setPlatforms(obj.getString("platforms"));
                games.setImage(obj.getString("image"));

                gamesList.add(games);
            }
            return gamesList;

        }
        catch (JSONException ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

 

How Volley Works And Handles Request.

Using volley we can use common request type very easily and fast without using/creating any AsyncTask, volley automatically handles all the Asynchronous functionality.

There are some basic and common  request type we can use.

  • StringRequest – You specify a URL and volley gives raw string in response.
  • ImageRequest – You specify a URL of an image and volley gives image in response.
  • JsonObjectRequest and JsonArrayRequest – You specify a URL and receive JSON object or array.

Below is the snippet from android developer site, is for only to make you understand how we can simply request a raw string using volley.

volley_request

that’s it 🙂 its very easy to fetch raw string.

 

 

Step D- Writing an GamesAdapter Class

 

Create a class GamesAdapter.java paste the following code. This is the adapter for our JSON data. As we saw how volley works and handle request, I used volle ImageRequest in GamesAdapter.java class, meaning that i am downloading image separately using volley in this class.


GamesAdapter.java
public class GamesAdapter extends BaseAdapter {

    private Context context;
    private List<Games> gamesList;
    private LayoutInflater inflater = null;

    public static final String IMAGE_BASEURL = "http://192.168.10.6/games_information/uploads/";

    private LruCache<Integer,Bitmap> imageCache;
    private RequestQueue queue;

    public GamesAdapter(Context context, List<Games> list) {

        this.context = context;
        this.gamesList = list;
        inflater = LayoutInflater.from(context);

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;
        imageCache = new LruCache<>(cacheSize);

        queue = Volley.newRequestQueue(context);
    }

    public class ViewHolder {

        TextView _title;
        TextView _desc;
        TextView _plateform;
        ImageView _gameImage;

    }

    @Override
    public int getCount() {
        return gamesList.size();
    }

    @Override
    public Object getItem(int position) {

        return gamesList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {


        final Games games = gamesList.get(position);
        final ViewHolder holder;
        if(convertView == null) {

            convertView = inflater.inflate(R.layout.list_item_templates,null);
            holder = new ViewHolder();

            holder._title = (TextView) convertView.findViewById(R.id.tvtitle);
            holder._desc = (TextView) convertView.findViewById(R.id.tvdesc);
            holder._plateform = (TextView) convertView.findViewById(R.id.tvplateform);

            convertView.setTag(holder);
        }
        else {

            holder = (ViewHolder) convertView.getTag();
        }

        holder._title.setText(games.getTitle().toString());
        holder._desc.setText(games.getDesc().toString());
        holder._plateform.setText(games.getPlatforms().toString());

        Bitmap bitmap = imageCache.get(Integer.parseInt(games.getId()));
        holder._gameImage = (ImageView) convertView.findViewById(R.id.gameImage);

        if (bitmap != null) {

            holder._gameImage.setImageBitmap(bitmap);

        }else {

            String imageURL = IMAGE_BASEURL +games.getImage();
            ImageRequest request = new ImageRequest(imageURL,
                    new Response.Listener<Bitmap>() {
                        @Override
                        public void onResponse(Bitmap response) {

                            holder._gameImage.setImageBitmap(response);
                            imageCache.put(Integer.parseInt(games.getId()), response);

                        }
                    },
                    90, 90,
                    Bitmap.Config.ARGB_8888,
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                            Log.d("error",error.getMessage().toString());
                        }
                    });
            queue.add(request);
        }
        return convertView;
    }

}

 

Putting it All Together

Now open MainActivity.java and put everything we created above. In the MainActivity.java class i am using Volley StringRequest for fetching raw string from the web and passing it to the GamesJSONParser.java class.

 

MainActivity.java
public class MainActivity extends AppCompatActivity {

    List<Games> gamesList;
    ListView lv;
    String uri = "http://192.168.10.6/games_information/showallgames.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv = (ListView) findViewById(R.id.listView);
        requestData(uri);


    }

    public void requestData(String uri) {

        StringRequest request = new StringRequest(uri,

                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        gamesList = GamesJSONParser.parseData(response);
                        GamesAdapter adapter = new GamesAdapter(MainActivity.this, gamesList);
                        lv.setAdapter(adapter);

                    }
                },

                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(MainActivity.this, error.getMessage().toString(), Toast.LENGTH_SHORT).show();
                    }
                });

        RequestQueue queue = Volley.newRequestQueue(this);
        queue.add(request);
    }


}

Now Congrates, you have successfully implmented JSON Parsing Volley in your Project.

 

Volley JSON Parsing

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

16 Comments

Leave a Comment