I am trying to post boolean value using volley library.When a button is clicked,a boolean value is set to true.The boolean value is then posted to my php script to increment counter in my mysql database. i am getting an error in trying to add a request to queue. What am i doing wrong? This is my code
holder.custom_button.setOnClickListener(new View.OnClickListener() {
int count;
#Override
public void onClick(View v) {
count = 0;
superHeroes.get(position).setCount(superHeroes.get(position).getCount() + 1);
holder.txtCount.setText(superHeroes.get(position).getCount() + "");
final String url = "http://10.0.2.2/likes.php";
isLiked = true;
JSONObject obj = new JSONObject();
try {
obj.put("isLiked", true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
// i am getting error here
customVolleyRequest.getInstance(this).addToRequestQueue(jsObjRequest);
}
});
SINGLETON
package net.simplifiedcoding.myfeed;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.ImageLoader;
/**
* Created by Belal on 12/5/2015.
*/
public class CustomVolleyRequest {
private static CustomVolleyRequest customVolleyRequest;
private static Context context;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private CustomVolleyRequest(Context context) {
this.context = context;
this.requestQueue = getRequestQueue();
imageLoader = new ImageLoader(requestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#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 CustomVolleyRequest getInstance(Context context) {
if (customVolleyRequest == null) {
customVolleyRequest = new CustomVolleyRequest(context);
}
return customVolleyRequest;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
requestQueue = new RequestQueue(cache, network);
requestQueue.start();
}
return requestQueue;
}
public ImageLoader getImageLoader() {
return imageLoader;
}
}
ERROR
'getInstance(android.content.Context)' in 'net.simplifiedcoding.myfeed.CustomVolleyRequest' cannot be applied to '(anonymous android.view.View.OnClickListener)'
You are not making POST request. You should do like this:
JsonObjectRequest req = new JsonObjectRequest( Request.Method.POST, url,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// Handle response
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle Error
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
AppController.getInstance().addToRequestQueue(req); // AppController is Volley Singleton.
You have used CardAdapter, I don't what that is. You should always add the request object to Volley Singleton. Reference.
Related
I am trying to implement a GET request using Volley. I have a button 'Apply' in PlacementActivity which directs the user to PlacementHomeActivity which has fragments. I have implemented the GET request in Apply.OnClickListener and the data received from the request must be shown in PlacementHomeActivity. But I get a null object error in this line:
SingletonRequestQueue.getInstance(PlacementActivity.context).addToRequestQueue(ArrayRequest);
(This code worked fine when Activity was used instead of Fragments)
This is the code of the Apply.OnClickListener class:
Apply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
applyList = new ArrayList<Company>();
JsonArrayRequest ArrayRequest = new JsonArrayRequest(Request.Method.GET, applyCompaniesUrl,
null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject companies = response.getJSONObject(i);
String id = companies.getString("id");
JSONObject company = companies.getJSONObject("company");
Company company = new Company(id, company);
applyList.add(company);
}
} catch (JSONException e) {
e.printStackTrace();
}
Intent applyListIntent = new Intent(PlacementActivity.this,
PlacementHomeActivity.class);
startActivity(applyListIntent);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PlacementActivity.this, error.toString(), Toast.LENGTH_LONG).show();
StringWriter writer = new StringWriter();
error.printStackTrace(new PrintWriter(writer));
String s = writer.toString();
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Cookie", "remember_user_token=" + userToken);
return params;
}
};
SingletonRequestQueue.getInstance(PlacementActivity.context).addToRequestQueue(ArrayRequest);
}
});
This is the SingletonRequestQueue class:
public class SingletonRequestQueue {
public static SingletonRequestQueue mInstance;
private RequestQueue mRequestQueue;
private static Context appContext;
public Context context;
private SingletonRequestQueue(Context context){
appContext = context;
mRequestQueue = getRequestQueue();
}
public static synchronized SingletonRequestQueue getInstance(Context context){
if(mInstance==null) {
mInstance = new SingletonRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
if(mRequestQueue==null){
mRequestQueue = new Volley().newRequestQueue(appContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> request){
getRequestQueue().add(request);
}
}
How do I fix this error?
It seems like a context problem, try replacing PlacementActivity.context for getApplicationContext()
SingletonRequestQueue.getInstance(Context.getApplicationContext()).addToRequestQueue(ArrayRequest);
I was looking for an easy way to make an HTTP post in Android with body, my api call should be like :
https:url/api/message?token=myToken&channel=Pew&text=someText&username=User
What I did is this, I created this class
Public class ApiCalls {
private static PostCommentResponseListener mPostCommentResponse;
private static Context mContext;
public ApiCalls(){
}
public static void postNewComment(Context context, final String message){
mContext = context;
String apiUrl = context.getResources().getString(R.string.api_url);
mPostCommentResponse.requestStarted();
RequestQueue queue = Volley.newRequestQueue(context);
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
queue.add(sr);
}
public interface PostCommentResponseListener {
public void requestStarted();
public void requestCompleted();
public void requestEndedWithError(VolleyError error);
}
}
But it doesn't work, it only shows app has stopped.
Is good to use Volley? Or you recommend to me to use other way? I used to use HttpClient but it's deprecated now...
What I'm missing?
Log error
java.lang.NullPointerException: Attempt to invoke interface method 'void com.package.ApiCalls$PostCommentResponseListener.requestStarted()' on a null object reference
You can send json body using volly as below two ways.
1. Using JsonObjectRequest
Map<String,String> params = new HashMap<String, String>();
params.put("token",mContext.getResources().getString(R.string.access_token));
params.put("channel","pew");
params.put("text", message);
params.put("username","User");
JsonObjectRequest request_json = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Process success response
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
});
// add the request object to the queue to be executed
queue.add(request_json);
2. Using JSON directly in request body
JSONObject jsonBody = new JSONObject();
jsonBody.put("token",mContext.getResources().getString(R.string.access_token));
jsonBody.put("channel","pew");
jsonBody.put("text", message);
jsonBody.put("username","User");
final String mRequestBody = jsonBody.toString();
StringRequest sr = new StringRequest(Request.Method.POST,apiUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Process success response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// handle error
}
}){
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody.getBytes("utf-8");
} catch (Exception e) {
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
// add the request object to the queue to be executed
queue.add((sr);
Initialise your mPostCommentResponse like this:
public ApiCalls(){
mPostCommmentResponse = (PostCommentResponseListener)mContext;
}
it will do you work and rest is fine. Thanks.
EDITED:
In Another Activity from where you want to call "ApiCall" class, do code like that:
new ApiCalls().postNewComment(AnotherActivity.this,"Your Messsage here");
and in method "postNewComment" do like this:
mContext = context;
mPostCommmentResponse = (PostCommentResponseListener)mContext;
Is it ok and understable??
I had implemented the volley request before and it was working perfectly, with some changes i did it stoped working like i want ( i will explain the changes after code).
So basicly i want to request to volley passing 4 parameters (the method, the url, the token and the data)
so i do something like this:
IResult mResultCallback2 = null;
public void sendFotoServer(){
String url = connectionTxt + "/fotos/" + specieId + "/plants";
HashMap<String,String> params = new HashMap<String, String>();
byte[] capture = encodeImage(b);
String encodedImage = Base64.encodeToString(capture,1);
Log.d("encodedImage",encodedImage);
params.put("base64", encodedImage);
params.put("lat",String.valueOf(photo.getLat()));
params.put("lon",String.valueOf(photo.getLon()));
params.put("alt",String.valueOf(photo.getAlt()));
params.put("date",photo.getTime());
JSONObject sendObj = new JSONObject(params);
PostPhotoVolleyCallback();
mVolleyService = new VolleyService(mResultCallback2, this);
mVolleyService.postDataVolley("POSTCALL", url, sendObj,token);
}
void PostPhotoVolleyCallback(){
mResultCallback2 = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
Log.d("HELLO","HELLOTHERE");
Log.d("resposta2",response.toString());
Intent intent = new Intent(SimiliarPhotos.this,PlantFeed.class);
startActivity(intent);
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
Log.d("HELLO",response.toString());
}
#Override
public void notifyError(String requestType, VolleyError error) {
Log.d("errorV",error.getStackTrace().toString());
}
};
}
i have defined a interface so i can reuse the calls to volley like this:
package com.example.afcosta.inesctec.pt.android.services;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.afcosta.inesctec.pt.android.interfaces.IResult;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* Created by FilipeCosta on 19/05/2017.
*/
public class VolleyService {
IResult mResultCallback = null;
Context mContext;
public VolleyService(IResult resultCallback, Context context){
mResultCallback = resultCallback;
mContext = context;
}
public void postDataVolleyAuth(final String requestType,String url,JSONObject sendObj){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null) {
mResultCallback.notifySuccess(requestType, response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (mResultCallback != null) {
mResultCallback.notifyError(requestType, error);
}
}
});
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
public void postDataVolley(final String requestType,String url,JSONObject sendObj,final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(url,sendObj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null) {
mResultCallback.notifySuccess(requestType, response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null) {
mResultCallback.notifyError(requestType,error);
}
}
}) {
#Override
public Map<String, String> getHeaders() {
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX", token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
public void getDataVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonArrayRequest jsonArray = new JsonArrayRequest(Request.Method.GET, url,null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonArray.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonArray);
}catch(Exception e){
}
}
public void getDataObjectVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null)
mResultCallback.notifySuccess(requestType, response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObjectRequest);
}catch(Exception e){
}
}
public void putDataVolley(final String requestType, String url, final String token){
try {
RequestQueue queue = Volley.newRequestQueue(mContext);
JsonObjectRequest jsonObj = new JsonObjectRequest(Request.Method.PUT,url,null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if(mResultCallback != null) {
mResultCallback.notifySuccess(requestType, response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if(mResultCallback != null) {
mResultCallback.notifyError(requestType,error);
}
}
}){
#Override
public Map<String, String> getHeaders(){
Map<String, String> headers = new HashMap<>();
Log.d("tokenXX",token);
headers.put("x-access-token", token);
return headers;
}
};
jsonObj.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsonObj);
}catch(Exception e){
}
}
}
the problem is that i get a response but just like 5 minutes later, something like this:
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
POST /fotos/10/plants - - ms - -
the only thing that i changed was the way i get the data on this activity, at begin my model was a serializable, i changed it to parcelable, i pass my image trough a file and convert it to byte[] and after base64, i tried to debug and all my data was present, any tip here?
Thanks :)
I want to get the variable "response" from the BDDRequest class for using it in a ListView in my MainActivity class, how i can do ?
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest(){}
public static void GetRequest(final Context t, UserEmployeeInfo User) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
}
Use an interface for it,
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import java.io.Serializable;
public class BDDRequest implements Serializable {
private final long serialVersionUID = 1L;
static private Activity activity;
public String req;
public BDDRequest() {
}
public static void GetRequest(final Context t, UserEmployeeInfo User, final Callback callback) {
activity = (Activity) t;
RequestQueue queue = Volley.newRequestQueue(t);
ParamsSend params = new ParamsSend();
params.setUser(User);
ParserJson<ParamsSend> pj = new ParserJson<>(params);
String strJson;
try {
strJson = pj.writeJSON();
} catch (JsonProcessingException e) {
strJson = "null";
}
final String data = strJson;
String REST_API_URL = "http://212.227.53.116:8080/WSmartgroom/rest/perso/request";
Log.d("lol", strJson);
StringRequest myReq = new StringRequest(Request.Method.PUT,
REST_API_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("reponse:", response);
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("That didn't work!", "Error");
callback.onError();
}
}) {
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
return data.getBytes();
}
};
queue.add(myReq);
}
public interface Callback {
void onSuccess(String response);
void onError();
}
}
And implement the interface on your class .
Use like this,
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.example.BDDRequest.Callback;
public class MainActivity extends FragmentActivity implements Callback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BDDRequest.GetRequest(this, new UserEmployeeInfo(), this);
}
#Override
public void onSuccess(String response) {
// Bind the data to the listview
}
#Override
public void onError() {
//Show fallback message here
}
}
You're declaring onResponse method. Inside it, response is a parameter. Why do you want to get a parameter which you're putting into? The question is not clear.
I am downloading data from a website and would like to put it in an ArrayList. I am downloading 2 forms, images and URLS.
ArrayList<String> artistNames = new ArrayList<String>();
ArrayList<String> artistImageURLS = new ArrayList<String>();
int chosen = 0;
public class nameGetterClass extends AsyncTask<Void, Void, String>{
Handler handle;
Document doc;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... strings) {
try {
String url = "http://www.billboard.com/charts/artist-100";
doc = Jsoup.connect(url).get();
Elements names = doc.select("div.chart-row__title > h2.chart-row__song");
for (Element p : names)
artistNames.add(p.text());
// Log.i("names,", p.text());
}
catch(IOException ex){
}
return null;
}
#Override `**<--- ERROR HERE: method does not override superclass**`
protected void onPostExecute(Void result) {
}
}
I get an error as described in the second last line.
This actually doesnt even add anything to the arraylist, what should I do now?
protected String doInBackground(Void... strings) {
try {
String url = "http://www.billboard.com/charts/artist-100";
doc = Jsoup.connect(url).get();
Elements names = doc.select("div.chart-row__title > h2.chart-row__song");
for (Elements p : names)
artistNames.add(p.text());
// Log.i("names,", p.text());
}
catch(IOException ex){
}
return null;
}
please update the line inside the foreach with Elements you put Element. If you have still any problem please try to paste the console output which will you got when run in emulator that one makes people understand what the real problem is.
Try to use with volley library . Its easy and updated
https://developer.android.com/training/volley/request.html
ArrayList<String> artistImageURLS = new ArrayList<String>();
String url = "http://my-json-feed";
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
artistImageURLS.add(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
and here the Singleton :
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mCtx;
private MySingleton(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<String, Bitmap>(20);
#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 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);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}