Error in Android Volley Syntax - android

sign_in_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
request=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),
"SUCCESS"+jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getApplicationContext(),Welcome.class));
}else {
Toast.makeText(getApplicationContext(),
"Error"+jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
, new Response.ErrorListener() {
public void onErrorResponse(VolleyError Object error)
{
}
}
})
{
#Override
protected Map<String,String> getParams() throws AuthFailureError
{
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("email",email.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
} }
There is an error in the following part:
stating misplaced token ','
new Response.ErrorListener()
{
public void onErrorResponse(VolleyError Object error)
}

sign_in_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
request=new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
if(jsonObject.names().get(0).equals("success")){
Toast.makeText(getApplicationContext(),
"SUCCESS"+jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new
Intent(getApplicationContext(),Welcome.class));
}else {
Toast.makeText(getApplicationContext(),
"Error"+jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
, new Response.ErrorListener() {
public void onErrorResponse(VolleyError Object error)
{
}
}
})
{
#Override
protected Map<String,String> getParams() throws AuthFailureError
{
HashMap<String,String> hashMap=new HashMap<String, String>();
hashMap.put("email",email.getText().toString());
hashMap.put("password",password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});

You've misplaced brackets everywhere. Try the below code,
request = new StringRequest(Request.Method.GET, URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.names().get(0).equals("success")) {
Toast.makeText(getApplicationContext(),
"SUCCESS" + jsonObject.getString("success"),
Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Welcome.class));
} else {
Toast.makeText(getApplicationContext(),
"Error" + jsonObject.getString("Error"),
Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("email", email.getText().toString());
hashMap.put("password", password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);

Related

Getting com.android.volly.ServerError

I built an android app which i build signup form. i am using volly for network call but com.android.volly.ServerError comes. i dont understand where i make mistake.
below is my code
try {
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean status = jsonObject.getBoolean("success");
if (status) {
Constants.user = new User(jsonObject.getString("id"), jsonObject.getString("name"), jsonObject.getString("name"), jsonObject.getString("image"), jsonObject.getString("image"), "", jsonObject.getString("gender"), jsonObject.getString("dob"), 0, 0, jsonObject.getString("sb_live_id"), jsonObject.getString("is_host"), jsonObject.getString("country"), "1", jsonObject.getString("firebase_id"), "", jsonObject.getString("level"), jsonObject.getString("bio"), false, "1");
startActivity(new Intent(UserInfoActivity.this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error != null)
Log.e("error", error.getLocalizedMessage() + "");
progressDialog.dismiss();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("name", txtfullname.getText().toString());
MyData.put("number", phoneNumber);
MyData.put("image", imgpath);
MyData.put("password", password);
MyData.put("city", etCity.getText().toString());
MyData.put("country", etCountry.getText().toString());
MyData.put("dob", txtage.getText().toString());
MyData.put("bio", txtbio.getText().toString());
MyData.put("gender", gendr);
MyData.put("firebase_password", password);
MyData.put("firebase_id", uid);
MyData.put("email", email);
return MyData;
}
};
MyStringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyRequestQueue.add(MyStringRequest);
} catch (Exception e) {
e.printStackTrace();
}

Send token header in json object paramater Volley post

I am using post method in volley. I searched and found that getHeader() is used to send header in request.The solution was to use JSONObject request instead of string request(which i am using currently) but is there a way of sending header through this method? Because in that case I will have to modify a lot of code in many classes. Sorry for the English, I am not a native speaker.
The request parameter is a json object. I am sending the parameters using following code.
mRequestQueue = Volley.newRequestQueue(getContext());
mStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response", "onResponse: " + response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("This is the error", "Error :" + error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
HashMap<String, String> params2 = new HashMap<String, String>();
params2.put("AssigneeId",userid);
params2.put("IssueStatus", "5");
return new JSONObject(params2).toString().getBytes();
}
};
mRequestQueue.add(mStringRequest);
This request also has StringRequest. Please use the getHeaders() in this way:
public void requestWithSomeHttpHeaders() {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.somewebsite.com";
StringRequest getRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("ERROR","error => "+error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("User-Agent", "Nintendo Gameboy");
params.put("Accept-Language", "fr");
return params;
}
};
queue.add(getRequest);
}
For JsonObjectRequest:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,url,
null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(tag, response.toString());
activity.hideDialog();
try {
activity.onRequestServed(response, code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag, "Error: " + error.getMessage());
Log.e(tag, "Site Info Error: " + error.getMessage());
Toast.makeText(activity.getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
activity.hideDialog();
try {
activity.onRequestServed(null,code);
} catch (JSONException e) {
e.printStackTrace();
}
}
}) {
/**
* Passing some request headers
*/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json");
headers.put("key", "Value");
return headers;
}
};

Could not allocate JNI Env

I'm updating my API every 2seconds,
but I am receiving this error and my application closes.
FATAL EXCEPTION: main
Process: com.application.toweeloasep, PID: 6681
java.lang.OutOfMemoryError: Could not allocate JNI Env
at java.lang.Thread.nativeCreate(Native Method)
at java.lang.Thread.start(Thread.java:730)
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.application.toweeloasep.fragments.Jobs$5$1.run(Jobs.java:260)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
After about a minute, it starts to crash and receives that error.
Am I overdoing things with Volley?
private void setRepeatingAsyncTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (checkRequests) {
RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
StringRequest mStringRequest = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.e("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", error.toString());
}
});
mRequestQueue.add(mStringRequest);
} else {
RequestQueue requestPlaceInfo = Volley.newRequestQueue(getActivity());
StringRequest request2 = new StringRequest(Request.Method.POST, "http://api.000.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
requestPlaceInfo.add(request2);
}
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 2000); // interval of one minute
}
OutOfMemoryError ... at com.android.volley.toolbox.Volley.newRequestQueue
Why do you need to create a new RequestQueue or StringRequest every two seconds?
Try making only one of each.
private final Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("ERR", String.valueOf(error));
}
};
private void setRepeatingVolleyTask() {
final RequestQueue mRequestQueue = Volley.newRequestQueue(getActivity());
final StringRequest trackRequest = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE:TRACK", response);
try {
JSONObject json = new JSONObject(response);
String mStatus = json.getString("status");
if (mStatus.equalsIgnoreCase("0")) {
Log.d("STATUS", mStatus);
} else if (mStatus.equalsIgnoreCase("1")) {
JSONArray infos = json.getJSONArray("data");
booking_id = infos.getJSONObject(0).getString("id");
user_address_location = infos.getJSONObject(0).getString("user_address_location");
mTxtBatteryInfo.setText(infos.getJSONObject(0).getJSONObject("battery").getString("model"));
mTxtUserLocation.setText(user_address_location);
checkRequests = false;
mJobsHome.setVisibility(View.GONE);
mJobRequest.setVisibility(View.VISIBLE);
if (!onTick) {
mCountDownTimer.start();
onTick = true;
}
}
} catch (Exception e) {
Log.e("ERR", e.toString());
}
}
}, errorListener );
final StringRequest trackRequest2 = new StringRequest(Request.Method.POST, "http://api.toweelo.com/booking/track", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, errorListener) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("booking_id", booking_id);
params.put("rider_long", String.valueOf(lng));
params.put("rider_lat", String.valueOf(lat));
return params;
}
};
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
// What are you trying to catch here??
try {
if (checkRequests) {
mRequestQueue.add(trackRequest);
} else {
mRequestQueue.add(trackRequest2);
} catch ( ... ) {
....
}
Note: You can use JsonObjectRequest instead of parsing JSON from a StringRequest

Activity leak while using volley listeners

I'm using volley library for sending requests and I have a memory leak. I traced it with leak canary and it seems to be from my requests mListeners. after some searching I cancel all my requests in my current activity but still I have a leak I could use some help thanks here is my download code:
(note: I use singleton pattern for getting volley request queue)
private void startImageDownloadService(final NEWS selectedNews) {
if (selectedNews.getIMG_URL() != null && !selectedNews.getIMG_URL().equals("null")) {
ImageRequest imageRequest = new ImageRequest(selectedNews.getIMG_URL(),
new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap bitmap) {
newsImage_imageView.setVisibility(View.VISIBLE);
newsImage_imageView.setImageBitmap(bitmap);
saveImageToFileStarter(bitmap, selectedNews);
}
}, 200, 200, null, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Failed to download image", Toast.LENGTH_SHORT).show();
}
});
imageRequest.setShouldCache(false);
MyVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(imageRequest, "newsActivityImage");
//
}
}
private void requestLike(final ImageButton likeButton, final long id) {
try {
StringRequest jsonRequest = new StringRequest(Request.Method.POST, G.likeURL + id + "/like",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
Log.e("requestLikeJson", s);
JSONObject likeObject = new JSONObject(s);
int likeNumbers = likeObject.getInt("likes");
// Toast.makeText(NewsActivity.this, likeNumbers + "", Toast.LENGTH_LONG)
// .show();
if (likeButton.getTag().equals("notliked")) {
setLikeChangeInDatabase(false, id, likeNumbers);
}
else{
setLikeChangeInDatabase(true, id, likeNumbers);
}
// viewsCount_textView.setText("" + likeNumbers);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(NewsActivity.this, "No Internet connection", Toast.LENGTH_LONG).show();
try {
volleyError.printStackTrace();
Log.e("network error", new String(volleyError.networkResponse.data));
} catch (Exception e) {
e.printStackTrace();
}
if (likeButton.getTag().equals("notliked")) {
likeButton.setTag("liked");
likeButtonImageSetter();
} else {
likeButton.setTag("notliked");
likeButtonImageSetter();
}
Animation shake = AnimationUtils.loadAnimation(NewsActivity.this, R.anim.actionfeedback);
likeButton.startAnimation(shake);
}
}) {
#Override
public Priority getPriority() {
return Priority.HIGH;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
Log.e("sent token", "Token " + G.token);
params.put("Authorization", "Token " + G.token);
params.put("Accept-Language", "en-US,en;q=0.8,fa;q=0.6,pt;q=0.4,ar;q=0.2,gl;q=0.2");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String utf8String = null;
try {
utf8String = new String(response.data, "UTF-8");
return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
G.socketTimeout,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonRequest, "like");
} catch (Exception e) {
}
}
private void requestView(long id) {
try {
StringRequest jsonRequest = new StringRequest(Request.Method.GET, G.viewURL + id + "/view", new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
JSONObject viewObject = new JSONObject(s);
Log.e("requestViewJson", s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
try {
volleyError.printStackTrace();
Log.e("network error", new String(volleyError.networkResponse.data));
} catch (Exception e) {
e.printStackTrace();
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
Log.e("sent token", "Token " + G.token);
params.put("Authorization", "Token " + G.token);
params.put("Accept-Language", "en-US,en;q=0.8,fa;q=0.6,pt;q=0.4,ar;q=0.2,gl;q=0.2");
return params;
}
#Override
public Priority getPriority() {
return Priority.HIGH;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String utf8String = null;
try {
utf8String = new String(response.data, "UTF-8");
return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
G.socketTimeout,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MyVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonRequest,"view");
} catch (Exception e) {
}
}
and in my onStop() I have :
#Override
protected void onStop() {
try {//new change
MyVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests("newsActivityImage");
MyVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests("view");
MyVolleySingleton.getInstance(getApplicationContext()).cancelPendingRequests("like");
loadImageFromFile.cancel(true);
loadImageFromFile=null;
}catch (Exception e){}
super.onStop();
}
After some researching I found that the volley listeners cause the activity leak because they are instantiated as anonymous classes and therefore hold an implicit reference to their outer class (in this example news activity) so I made a separate class for VolleyRequest (just to make them customizable not really related to the leak) and made a listener interface which I implement as an innerclass and use a weak reference to have access to the activity
request code :
public class MyVolleyStringRequest extends com.android.volley.toolbox.StringRequest {
StringResponseListener mListener;
public MyVolleyStringRequest(int method, String url, final StringResponseListener mListener) {
super(method, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
mListener.onSuccess(s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
mListener.onFailure(volleyError);
}
});
this.mListener = mListener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
Log.e("sent token", "Token " + G.token);
params.put("Authorization", "Token " + G.token);
params.put("Accept-Language", "en-US,en;q=0.8,fa;q=0.6,pt;q=0.4,ar;q=0.2,gl;q=0.2");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
try {
String utf8String = new String(response.data, "UTF-8");
return Response.success(utf8String, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
requestLike and requestView Code:
private void requestLike(final ImageButton likeButton, final long id) {
MyVolleyStringRequest likeRequest = new MyVolleyStringRequest(Request.Method.POST, G.likeURL + id + "/like",
new RequestLikeStringListener(this));
MyVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(likeRequest, "like");
}
private void requestView(long id) {
MyVolleyStringRequest viewRequest = new MyVolleyStringRequest(Request.Method.GET, G.viewURL + id + "/view",
new RequestViewStringListener());
MyVolleySingleton.getInstance(getApplicationContext()).addToRequestQueue(viewRequest, "view");
}
listener interface code :
public interface StringResponseListener {
void onSuccess(String response);
void onFailure(VolleyError error);
}
innerclasses code:
public static class RequestLikeStringListener implements StringResponseListener{
WeakReference<NewsActivity> contextWeakReference;
RequestLikeStringListener(NewsActivity context){
contextWeakReference = new WeakReference<>(context);
}
public void onSuccess(String response) {
try {
NewsActivity context = contextWeakReference.get();
if(context != null) {
ImageButton likeButton = (ImageButton) context.findViewById(R.id.likeButton);
Log.e("requestLikeJson", response);
JSONObject likeObject = new JSONObject(response);
int likeNumbers = likeObject.getInt("likes");
if (likeButton.getTag().equals("notliked")) {
context.setLikeChangeInDatabase(false, contextWeakReference.get().id, likeNumbers);
} else {
context.setLikeChangeInDatabase(true, contextWeakReference.get().id, likeNumbers);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onFailure(VolleyError error) {
NewsActivity context = contextWeakReference.get();
if(context != null) {
ImageButton likeButton = (ImageButton) context.findViewById(R.id.likeButton);
Toast.makeText(context, "No Internet connection", Toast.LENGTH_LONG).show();
try {
error.printStackTrace();
Log.e("network error", new String(error.networkResponse.data));
} catch (Exception e) {
e.printStackTrace();
}
if (likeButton.getTag().equals("notliked")) {
likeButton.setTag("liked");
context.likeButtonImageSetter();
} else {
likeButton.setTag("notliked");
context.likeButtonImageSetter();
}
Animation shake = AnimationUtils.loadAnimation(context, R.anim.actionfeedback);
likeButton.startAnimation(shake);
}
}
hope it helps someone!

Volley- fetching json array with POST request

I am using volley.jar to fetch JSON array from remote server. Am able to fetch via GET request.Please help me with POST request
I am following a tutorial from androidhive.
Here is my working code.
public class fbuk extends Activity {
// Movies json url
private static final String url = "http://example.com/xyz.php?q=ram";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
listView = (ListView) findViewById(R.id.listview);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("ttl"));
movie.setThumbnailUrl(obj.getString("img"));
movie.setRating(obj.getString("stts"));
movie.setYear(obj.getString("relz"));
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
How to send params
public void Post(String url, final Map<String, String> map) {
showProgress();
RequestQueue queue = Volley.newRequestQueue(_serverctx);
StringRequest request = new StringRequest(Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response!=null && response.length()>0) {
try {
_response.result(new JSONObject(response)); // Pass data to your parsing method(in my case i made a interface)
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("error");
hideProgres();
}
}){
#Override
protected Map<String, String> getParams() {
return map;
}
#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;
}
};
request.setShouldCache(false);
request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
queue.add(request);
}
Call from Activity or fragment
Put the above method in a seprate class and give a call like
Map<String,String> params = new HashMap<String, String>();
params.put("email",email);
params.put("password",password);
_req = new NetworkRequests(this, ctx);
_req.Post(ShoqahContants.Login_URL, params);
and your are Done :)
This worked for me.
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
url="http://www.example.com/xyz.php";
Volley.newRequestQueue(your_activity.this).add(
new CustomJsonRequest(Request.Method.POST, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
GC gc = new GC();
gc.setTitl(obj.getString("ttl"));
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
hidePDialog();
}
}) {
#Override
protected Response<JSONArray> parseNetworkResponse(
NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser
.parseCharset(response.headers));
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public class CustomJsonRequest extends Request {
Map<String, String> params;
private Response.Listener listener;
public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
Response.Listener responseListener, Response.ErrorListener errorListener) {
super(requestMethod, url, errorListener);
params=new HashMap<String, String>();
params.put("key", value);
this.params = params;
this.listener = responseListener;
}
#Override
protected void deliverResponse(Object response) {
listener.onResponse(response);
}
#Override
public Map<String, String> getParams() throws AuthFailureError {
return params;
}
#Override
protected Response parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
p.s:the json must be in the below format
[{"titl":"The Great gatsby"},{"titl":"Wolf Of Wall Street"}]

Categories

Resources