How do you use the Android Volley API?
Asked Answered
F

8

75

I am thinking of implementing the Android Volley library in my next projects (Google IO presentation about Volley).

However, I haven't found any serious API for that library.

How do I upload files, do POST/GET requests, and add a Gson parser as a JSON parser using Volley?

Source code

Fermium answered 10/7, 2013 at 13:21 Comment(3)
Go to this link java.dzone.com/articles/android-%E2%80%93-volley-library written by Stack Overflow User named Paresh Mayani.Phuongphycology
Check this out: afzaln.com/volley/overview-summary.htmlNonjuror
I've written about this here -> goo.gl/nl2DfNProduction
F
107

Edit: finally here it is an official training about "Volley library"

I found some examples about Volley library

  • Simple request
  • JSON request
  • Gson request
  • Image loading
  • with newer external HttpClient (4.2.3)
  • With Self-Signed SSL Certificate.
Fruition answered 10/7, 2013 at 13:58 Comment(2)
Interesting library and great links!! Thanks @Fruition ^^Bloodroot
I need help for PATCH requests with volley, can anyone help?Outport
I
10

Unfortunately there is no documentation for a Volley library like JavaDocs until now. Only repo on github and several tutorials across the Internet. So the only good docs is source code :) . When I played with Volley I read this tutorial.

About post/get you can read this : Volley - POST/GET parameters

Hope this helps

Interstate answered 10/7, 2013 at 13:27 Comment(0)
H
3

This is an illustration for making a POST request using Volley. StringRequest is used to get response in the form of String.
Assuming your rest API returns a JSON. The JSON response from your API is received as String here, which you can covert again to JSON and process it further. Added comments in code.

StringRequest postRequest = new StringRequest(Request.Method.POST, "PUT_YOUR_REST_API_URL_HERE",
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        final JSONObject jsonObject = new JSONObject(response);
                        // Process your json here as required
                    } catch (JSONException e) {
                        // Handle json exception as needed
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    String json = null;
                    NetworkResponse response = error.networkResponse;
                    if(response != null && response.data != null){
                        switch(response.statusCode) {
                            default:
                                String value = null;
                                try {
                                    // It is important to put UTF-8 to receive proper data else you will get byte[] parsing error.
                                    value = new String(response.data, "UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                                json = trimMessage(value, "message");
                                // Use it for displaying error message to user 
                                break;
                        }
                    }
                    loginError(json);
                    progressDialog.dismiss();
                    error.printStackTrace();
                }  
                public String trimMessage(String json, String key){
                    String trimmedString = null;
                    try{
                        JSONObject obj = new JSONObject(json);
                        trimmedString = obj.getString(key);
                    } catch(JSONException e){
                        e.printStackTrace();
                        return null;
                    }
                    return trimmedString;
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<>();
            params.put("abc", "pass abc");
            params.put("xyz", "pass xyz");
            // Pass more params as needed in your rest API
    // Example you may want to pass user input from EditText as a parameter
    // editText.getText().toString().trim()
            return params;
        }  
        @Override
        public String getBodyContentType() {
            // This is where you specify the content type
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    };

    // This adds the request to the request queue
    MySingleton.getInstance(YourActivity.this)
.addToRequestQueue(postRequest);

// Below is MySingleton class

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private static Context mCtx;  
    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(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(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }
}
Hung answered 19/4, 2016 at 18:0 Comment(0)
B
1

Just add volley.jar library to your project. and then

As per Android documentation :

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // process your response here

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        //perform operation here after getting error
    }            
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

For more help refer How to user Volley

Browbeat answered 13/3, 2015 at 9:49 Comment(0)
B
0

Use this class. It provides you an easy way to connect to the database.

public class WebRequest {

    private Context mContext;
    private String mUrl;
    private int mMethod;
    private VolleyListener mVolleyListener;

    public WebRequest(Context context) {
        mContext = context;
    }

    public WebRequest setURL(String url) {
        mUrl = url;
        return this;
    }

    public WebRequest setMethod(int method) {
        mMethod = method;
        return this;
    }

    public WebRequest readFromURL() {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        StringRequest stringRequest = new StringRequest(mMethod, mUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                mVolleyListener.onRecieve(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mVolleyListener.onFail(volleyError);
            }
        });

        requestQueue.add(stringRequest);
        return this;
    }

    public WebRequest onListener(VolleyListener volleyListener) {
        mVolleyListener = volleyListener;
        return this;
    }

    public interface VolleyListener {
        public void onRecieve(String data);

        public void onFail(VolleyError volleyError);
    }
}

Example usage:

new WebRequest(mContext)
     .setURL("http://google.com")
     .setMethod(Request.Method.POST)
     .readFromURL()
     .onListener(new WebRequest.VolleyListener() {
         @Override
         public void onRecieve(String data) {
         }

         @Override
         public void onFail(VolleyError volleyError) {
         }
     });
Bettis answered 3/7, 2017 at 14:55 Comment(3)
@Nagual use this link: computerworld.com/article/2702452/…Bettis
@Nagual Just add getParams method.Bettis
I don't think just adding the getParam method solves the whole purpose. Anyways I have figured out and did the desired changes in classNagual
H
0

In simple way

 private void load() {
    JsonArrayRequest arrayreq = new JsonArrayRequest(ip.ip+"loadcollege.php",
            new Response.Listener<JSONArray>() {

                @Override
                public void onResponse(JSONArray response) {

                    Album a;

                    try {
                        JSONArray data = new JSONArray(response.toString());
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject c = data.getJSONObject(i);
                            one = c.getString("cname").split(",");
                            two=c.getString("caddress").split(",");
                            three = c.getString("image").split(",");
                            four = c.getString("cid").split(",");
                            five = c.getString("logo").split(",");




                            a = new Album(one[0].toString(),two[0].toString(),ip.ip+"images/"+ three[0].toString(),four[0].toString(),ip.ip+"images/"+ five[0].toString());
                            albumList.add(a);

                        }
                        adapter.notifyDataSetChanged();


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            // The final parameter overrides the method onErrorResponse() and passes VolleyError
            //as a parameter
            new Response.ErrorListener() {
                @Override
                // Handles errors that occur due to Volley
                public void onErrorResponse(VolleyError error) {
                    Log.e("Volley", "Error");
                }
            }
    );
    // Adds the JSON array request "arrayreq" to the request queue
    requestQueue.add(arrayreq);
}
Heatstroke answered 8/2, 2018 at 20:40 Comment(0)
D
0

Before testing all of the above answers, include

compile 'com.android.volley:volley:1.0.0'

in your gradle file and don't forgot to add the Internet permission to your Manifest file.

Dekow answered 13/2, 2018 at 6:23 Comment(0)
V
0
private void userregister() {

  final  ProgressDialog pDialog = new ProgressDialog(this);
    pDialog.setMessage("Loading...");
    pDialog.show();

    RequestQueue queue = Volley.newRequestQueue(SignupActivity.this);
    String url = "you";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    pDialog.cancel();

                    try {
                        JSONObject jsonObject= new JSONObject(response.toString());
                        Log.e("status", ""+jsonObject.getString("status"));
                        if(jsonObject.getString("status").equals("success"))
                        {
                            String studentid=jsonObject.getString("id");
                            Intent intent=new Intent(SignupActivity.this, OTPVerificationActivity.class);
                            startActivity(intent);
                            finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.e("String ", ""+response);

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

        }
    }) {

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("password", input_password.getText().toString());
            params.put("cpassword", input_reEnterPassword.getText().toString());
            params.put("email", input_email.getText().toString());
            params.put("status", "1");
            params.put("last_name", input_lastname.getText().toString());
            params.put("phone", input_mobile.getText().toString());
            params.put("standard", input_reStandard.getText().toString());
            params.put("first_name", input_name.getText().toString());
            params.put("refcode", input_reReferal.getText().toString());
            params.put("created_at","");
            params.put("update_at", "");
            params.put("address", input_address.getText().toString());
            return params;
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);

Get full code here

Venule answered 4/3, 2019 at 13:0 Comment(1)
Never answer a question with only code. Explain what your code does and why it's better than the all other answers.Arlinda

© 2022 - 2024 — McMap. All rights reserved.