How to use Volley in fragments in Android? - java

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);

Related

arraylist = 'this' is not available, in Android Studio while adding element in the arraylist

I am fetching the json and adding the element to the arraylist. But, the element is not being add in the arraylist.
When I debugged, I found following at the debug point:
arraylist='this' is not available
I searched a lot but couldn't find the solution anywhere.
public class ProfileHeaderRepository {
private Context context;
private MutableLiveData<ArrayList<ProfileInfo>> mutableLiveData = new MutableLiveData<>();
private ArrayList<ProfileInfo> arrayList;
public ProfileHeaderRepository(Context context) {
this.context = context;
}
public LiveData<ArrayList<ProfileInfo>> getProfileDetails(){
String url = ApplicationConstants.GET_PROFILE_HEADER;
arrayList = new ArrayList<>();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject = (JSONObject) response.get(0);
String name = jsonObject.getString("extra_info");
String image = jsonObject.getString("thumbnail");
ProfileInfo profileInfo = new ProfileInfo(name, image);
arrayList.add(profileInfo);
} catch (JSONException e) {
e.printStackTrace();
}
mutableLiveData.postValue(arrayList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String key = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", null);
headers.put("Authorization","TOKEN "+key);
//return super.getHeaders();
return headers;
}
};
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
VolleySingleton.getInstance(context).addToRequestQueue(jsonArrayRequest);
return mutableLiveData;
}
}

Volley crashing app on service after long run

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).

passing one param to server and get array using JsonArrayRequest with volley android studio

I'm trying to make an app . I struggling to get some data of one of my table in my database . I know how to get everything from my table , but now i need only few lines of this table. So I have to pass an ID .
The problem is that i cant add any param in JsonArrayRequest.
You can see my php file and my class where I'm calling JsonArrayRequest:
php
<?php
include 'dbconfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user_id = $_POST["user_id"]; // this is what Im trying to fix
$sql = "SELECT * FROM plans WHERE user_id=?"; // and pass the information in ?
$result = $conn->query($sql);
if ($result->num_rows >0) {
// output data of each row
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>
java class:
public class PlansActivity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "http://travelb.000webhostapp.com/jsonData.php";
String JSON_ID = "user_id";
String JSON_NAME = "destination";
String JSON_SUBJECT = "date";
String JSON_PHONE_NUMBER = "plan_id";
Button button;
PostJsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_plans);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
button = (Button)findViewById(R.id.button) ;
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
final Intent intent = getIntent();
final int id = intent.getIntExtra("user_id", -1);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
JSON_DATA_WEB_CALL();
}
});*/
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setId(json.getInt(JSON_ID));
GetDataAdapter2.setName(json.getString(JSON_NAME));
GetDataAdapter2.setSubject(json.getString(JSON_SUBJECT));
GetDataAdapter2.setPhone_number(json.getString(JSON_PHONE_NUMBER));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
I read lot of thing but all different . Im new on androidstudio and php .
I hope someone can help me , because Im tryin to do that for 2weeks now .
You should extends JsonArrayRequest in your custom Request like this:
public class MyJsonArrayRequest extends JsonArrayRequest {
private Map<String, String> mPostParams;
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return mPostParams;
}
public MyJsonArrayRequest(String url, Map<String, String> postParams, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
this.mPostParams = postParams;
}
}
with getParams() method you will able to pass POST parameters.
Map<String, String> params = new HashMap<>();
params.put("ID", id);
params.put("USER_ID", userId);
MyJsonArrayRequest jsonArrayRequest = new MyJsonArrayRequest(GET_JSON_DATA_HTTP_URL, params,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
progressBar.setVisibility(View.GONE);
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Another way is to pass parameters via GET request in URL.
You can send parameters with jsonArrayRequest like this by overriding getParam method
JsonArrayRequest request = new JsonArrayRequest(method, url, null, responseListener, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
try {
params.put("paramOne", "hello");
} catch (JSONException e) {
e.printStackTrace();
}
return params;
}
};
addToRequestQueue(request);
#mcatta
I want to do something like I did in my others acticity :
ProfileRequest profilRequest = new ProfileRequest(id, responseListener);
RequestQueue queue = Volley.newRequestQueue(UserAreaActivity.this);
queue.add(profilRequest);
and
public class ProfileRequest extends StringRequest {
private static final String PROFIL_REQUEST_URL = "http://travelb.000webhostapp.com/Profil.php ";
private Map<String, String> params;
public ProfileRequest(int user_id, Response.Listener<String> listener){
super(Request.Method.POST, PROFIL_REQUEST_URL, listener, null);
params= new HashMap<>();
params.put("user_id", user_id+"");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
so the id in profilerequest is a final int variable.
this one was easy to do .
Im still confused with jsonarrayrequest
Its been a long time but,
someone can find it useful
and the following code works .
public class Activity extends AppCompatActivity {
List<GetDataAdapter> GetDataAdapter1;
RecyclerView recyclerView;
RecyclerView.LayoutManager recyclerViewlayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ProgressBar progressBar;
String GET_JSON_DATA_HTTP_URL = "API here";
//String JSON_ID = "id";
//we have intilize here with json names and database column name also should be kept here
String JSON_FNAME = "contact_fname";
String JSON_LNAME = "contact_lname";
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
//json web call from web
JSON_DATA_WEB_CALL();
}
public void JSON_DATA_WEB_CALL(){
String uid ="value"//Or you can use your value to pass
StringRequest strrequest = new StringRequest(Request.Method.POST,GET_JSON_DATA_HTTP_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
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("userid", uid);//userid to send to php
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(strrequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(String array) throws JSONException {
JSONArray jarr = new JSONArray(array);
for(int i = 0; i<jarr.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();//adapter class
//JSONObject json;
try {
JSONObject json = jarr.getJSONObject(i);
// JSONObject json = (JSONObject) array.get(String.valueOf(i));
//set and get methods should declare here with database colmun names and json names
GetDataAdapter2.setcontact_fname(json.getString(JSON_FNAME));
GetDataAdapter2.setcontact_lname(json.getString(JSON_LNAME));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}

Send data to Arraylist Android JSOUP

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;
}
}

How to post boolean value using volley

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.

Categories