Am implementing a service to get updates from server as below:
public class Myupdates extends Service {
private static final String TAG = "AutoUpdates";
private static final int started = 0;
static SQLiteDatabase db;
private boolean isRunning = false;
private CountDownTimer timer;
#Override
public void onCreate() {
this.db = openOrCreateDatabase("db", Context.MODE_PRIVATE, null);
//Log.i(TAG, "Service onCreate");
isRunning = true;
}
int mCount = 1;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.i(TAG, "Service onStartCommand");
//Creating new thread for my service
//Always write your long running tasks in a separate thread, to avoid ANR
new Thread(new Runnable() {
#Override
public void run() {
if (isRunning) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
updates();
}
}, 0, 30000);
}
//Stop service once it finishes its task
//stopSelf();
}
}).start();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
//Log.i(TAG, "Service onBind");
return null;
}
#Override
public void onDestroy() {
isRunning = false;
//Log.i(TAG, "Service onDestroy");
}
/*
HANDLE ADVERTS
*/
protected void updates() {
/*
JSON
*/
final JSONObject json = new JSONObject();
final JSONObject manJson = new JSONObject();
try {
manJson.put("userid", "4444");
manJson.put("version", "6.0");
final String j = json.put("UPDATE", manJson).toString();
final String base_url = "https://myweburl.com";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, base_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Log.i(TAG, "received "+response);
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String update = object.getString("UPDATE");
} catch (JSONException e) {
return;
}
return;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//perform operation here after getting error
return;
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
//pack message into json
try {
params.put("data", j.toString());
} catch (Exception e) {
//Log.i(TAG,"Map error: Unable to compile post");
}
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;
}
};
// Add the request to the RequestQueue.
queue.add(stringRequest);
// ends here
return;
} catch (Exception e) {
//Log.i(TAG,"ERROR: Unable to get setup settings");
} // end exception write
return;
}
}
However, after a long running of the service the app is crashing with the below error:
03-08 00:19:41.570 11239-11253/com.mobiledatabook.com.dialcode
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.mobiledatabook.com.dialcode, PID: 11239
java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes)
failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at com.android.volley.RequestQueue.start(RequestQueue.java:152)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at
com.mobiledatabook.com.dialcode.Myupdates.iDialAutoUpdates(Myupdates.java:128)
at
com.mobiledatabook.com.dialcode.Myupdates$1$1.run(Myupdates.java:74)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Error: java.lang.OutOfMemoryError.
Could someone help me to improve this code so as to avoid crashing the app after long running of the service?
This is occurring because you are creating the RequestQueue instance multiple times by passing the activity context. You should create the instance once using an Application class and then use it again and again whenever needed. Create an application class like this,
public class AppController extends Application {
private static AppController sInstance;
private RequestQueue mRequestQueue;
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public static synchronized AppController getInstance() {
return sInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
}
Then use it like this
RequestQueue queue=AppController.getInstance().getRequestQueue();
NOTE : By passing the context to request queue again and again , you are filling up your ram, which leads to an OutOfMemoryException when no more space can be allocated
As mentioned in android's official docs here ,
A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
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 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;
}
}
I am using Volley library to communicate with my database. I use recursive function to check continuously my database but after a period of time seems like the recursive function stop working and I get the following error:
FATAL EXCEPTION: main
Process: com.example.sakis.loginregister, PID: 22637
java.lang.OutOfMemoryError: pthread_create (stack size 131072 bytes) failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at com.android.volley.RequestQueue.start(RequestQueue.java:145)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:66)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at com.example.sakis.loginregister.MultiPlayerActivity.func(MultiPlayerActivity.java:342)
at com.example.sakis.loginregister.MultiPlayerActivity$2.onResponse(MultiPlayerActivity.java:160)
at com.example.sakis.loginregister.MultiPlayerActivity$2.onResponse(MultiPlayerActivity.java:133)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
I think it is a stackoverflow error when i dont get the proper response in time.Here is the recursive function code that i first call in onCreate method:
void func(){
reject=0;
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
request = jsonResponse.getInt("request");
requestorigin = jsonResponse.getString("requestorigin");
category = jsonResponse.getInt("category");
dif_level = jsonResponse.getInt("dif_level");
number_of_questions = jsonResponse.getInt("number_of_questions");
time_of_answer = jsonResponse.getInt("time_of_answer");
if(request==0) {
func();
}
if (request == 1) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MultiPlayerActivity.this,R.style.myBackgroundStyle);
alertDialogBuilder.setMessage("Έχεις νέο αίτημα από τον χρήστη " + requestorigin + "\n" + "Κατηγορία Ερωτήσεων: " + array_category[category]
+ "\n" + "Επίπεδο Δυσκολίας: " + array_dif_level[dif_level] + "\n" + "Αριθμός Ερωτήσεων: " + number_of_questions + "\n "
+ "Χρόνος Απάντησης: " + time_of_answer);
alertDialogBuilder.setPositiveButton("Ναι", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
SendResponseRequest sendResponseRequest = new SendResponseRequest(username, response1Listener);
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(sendResponseRequest);
Response.Listener<String> responseListener=new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success1=jsonResponse.getBoolean("success1");
if(success1) {
Intent intent2 = new Intent(MultiPlayerActivity.this, MultiPlayerGame2Activity.class);
intent2.putExtra("username1",username);
intent2.putExtra("username2",requestorigin);
intent2.putExtra("category", category);
intent2.putExtra("dif_level", dif_level);
intent2.putExtra("number_of_questions", number_of_questions);
intent2.putExtra("time_of_answer", time_of_answer);
intent2.putExtra("level", level);
intent2.putExtra("score", score);
intent2.putExtra("music",music);
intent2.putExtra("sound",sound);
startActivity(intent2);
// android.os.Process.killProcess(android.os.Process.myPid());
finish();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
Back0Request back0Request = new Back0Request(username,responseListener);
RequestQueue queue = Volley.newRequestQueue(MultiPlayerActivity.this);
queue.add(back0Request);
}
});
alertDialogBuilder.setNegativeButton("Όχι", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Response.Listener<String> response1Listener = new Response.Listener<String>() {
#Override
public void onResponse(final String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
reject = jsonResponse.getInt("reject");
if(reject==1) {
func();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
RejectRequestRequest rejectRequestRequest = new RejectRequestRequest(username, response1Listener);
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(rejectRequestRequest);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
} catch (JSONException e)
{
e.printStackTrace();
}
}
};
//text2.setText("OK");
CheckRequest checkRequest = new CheckRequest(username, response1Listener);
/***
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
checkRequest.setRetryPolicy(policy);
******/
RequestQueue queue1 = Volley.newRequestQueue(MultiPlayerActivity.this);
queue1.add(checkRequest);
//text3.setText("After ");
}
When the variable requests that I take from the database has a zero value I want to check the database again until it will take a non-zero value. Is there any better way to achieve that so I can avoid recursion because it will cause some overflow errors.
Problem solved when i use Singleton Pattern and re-use the same instance of the queue so i prevent out of memory error:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private MySingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new MySingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}
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.