Basic Use of Google Open Source Network Communication Library Volley

Keywords: Android JSON Google network

This article mainly refers to: http://developer.android.com/training/volley/index.html
  
According to Google's official statement, Volley is mainly suitable for scenarios where data is small but communication is frequent. This article mainly talks about some basic usage. I haven't studied Volley's implementation principle for the time being.
Google recommends using a singleton class to manage all Volley's network requests. Here's my current singleton class:

package com.android.etuan.whereru;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class MyVolleySingleton {

    private static MyVolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mContext;

    private MyVolleySingleton(Context context) {
        mContext = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {

                    //The Cache Size Computing Method Officially Recommended by Google
                    int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
                    int cacheSize = maxMemory / 8;

                    private final LruCache<String, Bitmap>
                            cache = new LruCache<>(cacheSize);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });

    }

    public static synchronized MyVolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MyVolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }

}

For general APP, get and post are enough to solve most of the problems (although it seems that neither Get nor Post need to be specified when Volley requests). Here are some of the codes I used to request school name list data (with some of the less relevant codes deleted): __________

//Data from drop-down lists

mSchoolList = new ArrayList<>();

//Request school name data
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
        InterfaceConstant.SCHOOL_NAME_LIST_URL,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                mSchoolList = new ArrayList<>();
                for (int i = 0;i < jsonArray.length();i++) {
                    try {
                        mSchoolList.add(jsonArray.getJSONObject(i).getString("name"));
                    } catch (JSONException e) {
                        System.out.println("JSON Parsing error SchoolList");
                    }
                }
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
MyVolleySingleton.getInstance(this.getApplicationContext())
        .addToRequestQueue(jsonArrayRequest);

As far as function implementation is concerned, it is extremely simple (of course, because the JSON data to be parsed here is very simple, and the data is parsed here only once, so it is parsed here directly). I generally use the following methods at present:

package com.android.etuan.whereru.utils.jsonjavabean;

import org.json.JSONException;
import org.json.JSONObject;

public class Person {

    private static Person sPerson;

    private Person() {
    }

    public static synchronized Person getInstance() {
        if (sPerson == null) {
            sPerson = new Person();
        }
        return sPerson;
    }

    private final String EroMsg = "JSON Parsing error Person";

    private String m_id;
    private int mTtl;
    private String mCreated;
    private String mUserId;
    private String mName;
    private String mSchool;
    private String mPhone;
    private String mSign;

    public String getM_id() {
        return m_id;
    }

    public String getmCreated() {
        return mCreated;
    }

    public int getmTtl() {
        return mTtl;
    }

    public String getmUserId() {
        return mUserId;
    }

    public String getmName() {
        return mName;
    }

    public String getmSchool() {
        return mSchool;
    }

    public String getmPhone() {
        return mPhone;
    }

    public String getmSign() {
        return mSign;
    }


    public void getInfoFromJson(JSONObject jsonObject) {
        try {
            m_id = jsonObject.getString("id");
        } catch (JSONException e) {
            System.out.println(EroMsg + "id");
        }
        try {
            mTtl = jsonObject.getInt("ttl");
        } catch (JSONException e) {
            System.out.println(EroMsg + "ttl");
        }
        try {
            mCreated = jsonObject.getString("created");
        } catch (JSONException e) {
            System.out.println(EroMsg + "created");
        }
        try {
            mUserId = jsonObject.getString("userId");
        } catch (JSONException e) {
            System.out.println(EroMsg + "userId");
        }
        try {
            JSONObject jsonUser = jsonObject.getJSONObject("user");
            try {
                mPhone = jsonUser.getString("phone");
            } catch (JSONException e) {
                System.out.println(EroMsg + "phone");
            }
            try {
                mName = jsonUser.getString("name");
            } catch (JSONException e) {
                System.out.println(EroMsg + "name");
            }
            try {
                mSchool = jsonUser.getString("school");
            } catch (JSONException e) {
                System.out.println(EroMsg + "school");
            }
            try {
                mSign = jsonUser.getString("sign");
            } catch (JSONException e) {
                System.out.println(EroMsg + "sign");
            }

        } catch (Exception e) {
            System.out.println("JSON Parsing error User");
            e.printStackTrace();
        }
    }

}

For example, the user information above will be used in many interfaces of APP. There is no need to make a network request every time it is used, so a single class is directly used for storage and direct invocation.
The code parsed by JSON above is also thrown directly into the singleton class. The amount of code is not large, so it is not necessary to make a class to do data parsing alone. I don't use the same above. Gson This framework to do parsing, first, we have to parse JSON data is not too large, second, it seems that the back-end JSON data is not very legitimate ah, always all kinds of problems, tossing and turning, I found that if I wrote early, of course, it may also be my own Gson's inexperience caused by...
See above to get the JSONArray type, in fact, JSONObject is similar:

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
InterfaceConstant.SCHOOL_ACTIVITY_URL, null,
new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject jsonObject) {

    }
},
new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError volleyError) {

    }
});
MyVolleySingleton.getInstance(this.getApplicationContext())
    .addToRequestQueue(jsonObjectRequest);

Here's how to get pictures from the server with Volley. Here's the code of Adadapter for loading ListView of Campus Activities, which uses this part of knowledge:

package com.android.etuan.whereru.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.etuan.whereru.MyVolleySingleton;
import com.android.etuan.whereru.R;
import com.android.etuan.whereru.utils.jsonjavabean.mActivity;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;

public class CampusActivityListViewAdapter extends BaseAdapter {

    private Context mContext;
    private List<mActivity> mActivityDataList;
    private LayoutInflater mLayoutInflater;

    //Get rid of the work that needs to be done in the constructor to avoid repetition in getView
    public CampusActivityListViewAdapter(Context context) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(mContext);
    }


    public void setmActivityDataList(List<mActivity> mActivityDataList) {
        this.mActivityDataList = mActivityDataList;
    }

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

    @Override
    public Object getItem(int position) {
        return mActivityDataList.get(position);
    }

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

    public static class ViewHolder {
        public TextView activityTitleTextView;
        public TextView activitySponsorTextView;
        public TextView activityCreateTimeTextView;
        public TextView activityKeywordTextView;

        public NetworkImageView activityPosterImageView;
    }

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

        ViewHolder viewHolder = null;

        if (convertView == null) {

            convertView = mLayoutInflater
                    .inflate(R.layout.campus_activity_home_page_activity_listview_item_layout, null);

            viewHolder = new ViewHolder();

            viewHolder.activityTitleTextView = (TextView)
                    convertView.findViewById(R.id.activity_title);
            viewHolder.activitySponsorTextView = (TextView)
                    convertView.findViewById(R.id.activity_sponsor);
            viewHolder.activityCreateTimeTextView = (TextView)
                    convertView.findViewById(R.id.activity_create_time);
            viewHolder.activityKeywordTextView = (TextView)
                    convertView.findViewById(R.id.activity_keyword);

            viewHolder.activityPosterImageView = (NetworkImageView)
                    convertView.findViewById(R.id.activity_poster);

            //Set default images during loading
            viewHolder.activityPosterImageView.setDefaultImageResId(R.drawable.loading_image);
            //Set the picture when loading error occurs
            viewHolder.activityPosterImageView.setErrorImageResId(R.drawable.loading_image_error);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.activityTitleTextView.setText(mActivityDataList.get(position).getTitle());
        viewHolder.activitySponsorTextView.setText(mActivityDataList.get(position).getAuthorName());
        viewHolder.activityCreateTimeTextView.setText(mActivityDataList.get(position).getCreated());
        viewHolder.activityKeywordTextView.setText(mActivityDataList.get(position).getKeyword());

        //Here, Volley is used to load pictures, which are placed in the Network Image View.
        viewHolder.activityPosterImageView.setImageUrl(
                mActivityDataList.get(position).getImgUrl(),
                MyVolleySingleton.getInstance(mContext.getApplicationContext()).getImageLoader());

        return convertView;

    }

}  

In fact, the core of the code is a sentence: ____________

viewHolder.activityPosterImageView.setImageUrl(mActivityDataList.get(position).getImgUrl(),MyVolleySingleton.getInstance(mContext.getApplicationContext()).getImageLoader());

If your singleton class has been written and JSON has been parsed, notice to replace the ImageView with the NetworkImageView control.
  
By the way, let's give you an example of post. There seems to be no post-related examples in the tutorial that Google gave us. For example, when a user registers, he will use post. The code is as follows (Similarly, some code with low correlation is deleted):

Map<String, String> params = new HashMap<>();
params.put("name", userName);
params.put("password", password);
params.put("phone", phoneNumber);
params.put("sex", mSexChooseResult);
params.put("school", mSchoolName);

JSONObject jsonObject = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(
        InterfaceConstant.REGISTER_URL, jsonObject,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
MyVolleySingleton.getInstance(RegisterPageTwoActivity.this.getApplicationContext())
        .addToRequestQueue(jsonRequest);

Posted by naveenbj on Wed, 27 Mar 2019 04:39:30 -0700