Android Volley NullPointerException without any explanation - android

I have 3 functions that are uploading images and setting the name of an image on a server. The thing is, I can't get all functions to work at a time. Only one function works and the other throws a NullPointerException that aren't pointing to anything specific but just the first line in the function.
private void uploadMainImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_MAIN , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Main]: " + response.toString());
uploadThumbImage();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", pp_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void uploadThumbImage()
{
RequestQueue queue = Volley.newRequestQueue(getActivity());
StringRequest ppRequest = new StringRequest(Request.Method.POST,URL_IMAGE_THUMB , new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
System.out.println("Response[Job Image Thumb]: " + response.toString());
//updateImageName();
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
System.out.println("Job Thumb Image profile Error: " + error.getMessage());
progressDialog.hide();
progressDialog.dismiss();
}
})
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("ImageName",jobID + "-1.jpg");
params.put("base64", thumb_finalImage);
return params;
}
};
queue.add(ppRequest);
}
private void updateImageName()
{
SharedPreferences prefs = getActivity().getSharedPreferences("USER_DETAILS", Context.MODE_PRIVATE);
String userID = prefs.getString("USER_ID", "NO_SESSION");
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
Map<String, String> params = new HashMap<String, String>();
params.put("postpicture ", jobID + "-1.jpg");
params.put("userid", "1");
params.put("postjobid ", jobID);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,URL + "updateJobPostImage" ,new JSONObject(params), new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
Log.d(LOG_TAG,"Response[Image Name Update Job]: " + response.toString());
try
{
String status = response.getString("result");
if(status.equals("Success"))
{
progressDialog.hide();
progressDialog.dismiss();
}
else
{
Log.d(LOG_TAG," Image Name Update Failed, Aborting.");
progressDialog.hide();
progressDialog.dismiss();
}
}
catch (JSONException e)
{
Log.d(LOG_TAG,e.getMessage());
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
progressDialog.dismiss();
Log.d(LOG_TAG, "Image Name Update Error: " + error.getMessage());
}
});
queue.add(request);
}
This is the log
04-30 00:41:29.074 14041-14041/com.antisaby.trackit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.antisaby.trackit, PID: 14041
java.lang.NullPointerException
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:43)
at com.android.volley.toolbox.Volley.newRequestQueue(Volley.java:78)
at fragments.homefragments.AddServiceFragment.uploadThumbImage(AddServiceFragment.java:397)
at fragments.homefragments.AddServiceFragment.access$1100(AddServiceFragment.java:50)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:368)
at fragments.homefragments.AddServiceFragment$8.onResponse(AddServiceFragment.java:363)
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:5322)
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:829)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:645)
The uploadMainImage function executes first. If the response is good, it calls uploadThumbImage. If the result of uploadThumbImage is good, it calls updateImageName. If i don't comment out any function, the exception occurs in the uploadThumbImage function. If i comment out the first function, exception occurs in the last function. If I try to catch the exception, the message comes out to be null.

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

Related

Can't call the server using volley library?

i am posting data to the server and while debugging i get the following error at this line. and unable to call the server.
network calls. i am using sql server version 2014, and the url to web services is localhost:8081/api/login/signup.
StringRequest strReq = new StringRequest(Request.Method.POST, Constants.SIGN_UP,new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Snackbar.make(mainlayout, response.toString(), Snackbar.LENGTH_LONG).show();
Log.e("Responce from server", response);
avi.hide();
if(!response.contains("User")) {
spEdit.putString(getString(R.string.uaccount), response);
spEdit.commit();
Intent intent = new Intent(SignUp.this, Products.class);
intent.putExtra(getString(R.string.uemail), Email_Address);
intent.putExtra(getString(R.string.uphone), Phone_Number);
intent.putExtra(getString(R.string.upass), Password);
startActivity(intent);
finish();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
avi.hide();
Log.e("Volley Error", error.toString());
if(error.toString().contains("NoConnectionError")) {
Snackbar.make(mainlayout, "Internet Not Available!", Snackbar.LENGTH_LONG).show();
}else{
Snackbar.make(mainlayout, "Webservice not responding!", Snackbar.LENGTH_LONG).show();
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<String, String>();
String name[] = Name.split(" ");
String first = "", last = "";
boolean firstb = true;
for (int i = 0; i < name.length; i++) {
if (firstb) {
first += name[i];
firstb = false;
} else {
if (i == name.length - 1) {
last = name[i];
} else {
first += " ";
first += name[i];
}
}
}
data.put("FirstName", first);
data.put("LastName", last);
data.put("LoginName", Login_Name);
data.put("PrimaryEmail", Email_Address);
data.put("PrimaryPasscode", Encrypted_Password);
data.put("PhoneNumber", Phone_Number);
data.put("MobileVerificationCode", smsCode);
data.put("AccountType", UserType);
return data;
}
};
AppController.getInstance().addToRequestQueue(strReq, REQ_TAG);
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: market.enxo.com.marketstore, PID: 3202
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
at com.android.volley.Request.<init>(Request.java:136)
at com.android.volley.toolbox.StringRequest.<init>(StringRequest.java:43)
at market.enxo.com.marketstore.SignUp$8.<init>(SignUp.java:361)
at market.enxo.com.marketstore.SignUp.signUpWS(SignUp.java:332)
at market.enxo.com.marketstore.SignUp$4.onClick(SignUp.java:297)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

How to use Call Type with EventBus

I am using EventBus to notify Activity/Fragment when I get response from the server. Everything works good so far, but problem arises when I consume two network calls in same Fragment or Activity. The problem is the same method onEvent(String response) get calls for both responses from server. The response of call 1 is different from call 2.
I came up with a solution - I added CallType in NetworkReqest but I can't notify the activity/fragment about the network call since post() takes only one parameter.
Here is the relevant code -
public class NetworkRequest {
EventBus eventBus = EventBus.getDefault();
public void stringParamRequest(String url, final Map<String, String> params,String callType) {
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
eventBus.post(error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = params;
return param;
}
};
SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
}
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
}
Method Inside the fragment/activity Here arise the problem when after getting the response from one request i fire another request which is dependent of the respose of the first request
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(String response) {
Log.d(TAG, response);
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
isCourseAvaible = true;
List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
} else {
Log.d(TAG, response);
}
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getActivity(), "Something went wrong " + error.toString(), Toast.LENGTH_SHORT).show();
}
How can I differentiate the callType within onEvent(). Some guidance is required. Thanks much.
One option is to wrap the two pieces of data you need into a class and pass that to event bus. Leaving off private members, getters/setters and constructors for brevity.
class NetworkResponse() {
public String callType;
public String response;
}
When you get a response, allocate a NetworkResponse and populate it with the response and the call type and post that to the event bus.
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(NetworkResponse networkResponse) {
if(networkResponse.callType.equals(CALL_1)) {
// ...
} else if (networkResponse.callType.equals(CALL_2)) {
// ...
}
}
Serialize the String response to a java bean in the onResponse method, and emit the right object to the views. Activities, Fragments and Views have no need to know about serialization, and besides, your app's performance can improve, since you can modify your code to serialize the data in a background thread.
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(AppMgr.coursesMgr(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
Then your first event subscription will look like this:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(List<CoursesDTO> coursesDTOs) {
Log.d(TAG, response);
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
isCourseAvaible = true;
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
} else {
Log.d(TAG, response);
}
}
and you can have a second, different, String subscription. But since you are going to make the second call anyway, it would be best to execute it directly after getting the right answer from the first one.
public class NetworkRequest {
EventBus eventBus = EventBus.getDefault();
public void stringParamRequest(String url, final Map<String, String> params,String callType) {
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
eventBus.post(error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = params;
return param;
}
};
SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
}
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
}
Finally, this two lines
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
are superfluous, is like having no condition.

Error in OTP verification code android

I am Creating an application which perform an OTP verification method..
I implemented the code as described in this link http://www.androidhive.info/2015/08/android-adding-sms-verification-like-whatsapp-part-2/
But when i click the NEXT button in app app is force closing
The function i get error is :
private void requestForSMS(final String name, final String email, final String mobile) {
StringRequest strReq = new StringRequest(Request.Method.POST,
Config.URL_REQUEST_SMS, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject responseObj = new JSONObject(response);
// Parsing json object response
// response will be a json object
boolean error = responseObj.getBoolean("error");
String message = responseObj.getString("message");
// checking for error, if not error SMS is initiated
// device should receive it shortly
if (!error) {
// boolean flag saying device is waiting for sms
pref.setIsWaitingForSms(true);
// moving the screen to next pager item i.e otp screen
viewPager.setCurrentItem(1);
txtEditMobile.setText(pref.getMobileNumber());
layoutEditMobile.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Error: " + message,
Toast.LENGTH_LONG).show();
}
// hiding the progress bar
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
//Toast.makeText(getApplicationContext(),"Error: " + e.getMessage(),Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Log.e(TAG, "Error: " + error.getMessage());
//Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}) {
/**
* Passing user parameters to our server
* #return
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("mobile", mobile);
//Log.e(TAG, "Posting params: " + params.toString());
return params;
}
};
// Adding request to request queue
MyApplication.getInstance().addToRequestQueue(strReq);
}
Log is :
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.my.application.activity.SmsActivity.requestForSMS(SmsActivity.java:245)
at com.my.application.activity.SmsActivity.validateForm(SmsActivity.java:157)
at com.my.application.activity.SmsActivity.onClick(SmsActivity.java:117)
at android.view.View.performClick(View.java:4211)
at android.view.View$PerformClick.run(View.java:17446)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:153)
at android.app.ActivityThread.main(ActivityThread.java:5336)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)
Volley library is used..
Any help??
public void confirmOTP() throws JSONException {
LayoutInflater lf = LayoutInflater.from(SignUp.this);
View view = lf.inflate(R.layout.confirm_dialog, null);
confirmButton = (Button) view.findViewById(R.id.buttonConfirm);
inputOTP = (EditText) view.findViewById(R.id.editTextOtp);
AlertDialog.Builder dialog = new AlertDialog.Builder(SignUp.this);
dialog.setView(view);
final AlertDialog alertDialog = dialog.create();
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alertDialog.dismiss();
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Authenticating", "Please Wait ...", false, false);
load.setCanceledOnTouchOutside(false);
final String otp = inputOTP.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, ConfingDetalsActivity.CONFIRM_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Confirm Response Check>",response.toString());
String mesage;
try {
JSONObject jsonObject=new JSONObject(response);
mesage=jsonObject.getString("msg");
if(mesage.equals("success")){
Toast.makeText(SignUp.this, "Registerd sucessfully", Toast.LENGTH_LONG).show();
load.dismiss();
Intent in = new Intent(SignUp.this, SignupSucess.class);
startActivity(in);
} else {
load.dismiss();
Toast.makeText(SignUp.this, "Wrong OTP Please try again", Toast.LENGTH_SHORT).show();
confirmOTP();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map params = new HashMap();
//Adding the parameters otp and username
params.put(ConfingDetalsActivity.KEY_OTP, otp);
if (businessFrag) {
} else {
params.put(ConfingDetalsActivity.CONSUMER_EMAIL, constant.EMAIl);
}
return params;
}
};
requestQueue.add(stringRequest);
}
});
}
public void register() {
Log.d("RegisterCalled>>>>>>>>>", "register");
final ProgressDialog load = ProgressDialog.show(SignUp.this, "Loading", "Pleas wait...", false, false);
load.setCanceledOnTouchOutside(false);
StringRequest request = new StringRequest(Request.Method.POST, ConfingDetalsActivity.REGISTER_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Response Check>>>",response.toString());
load.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
String message=jsonObject.getString("msg");
if (message.equals("success")) {
confirmOTP();
} else {
Toast.makeText(SignUp.this, "User Name or phone already register", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
load.dismiss();
Toast.makeText(SignUp.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parms = new HashMap<String,String>();
if (businessFrag) {
parms.put(ConfingDetalsActivity.BUSINESS_ZIP_CODE, constant.B_ZIP_CODE);
parms.put(ConfingDetalsActivity.BUSINESS_INDUSTRY, constant.B_INDUSTRY);
parms.put(ConfingDetalsActivity.BUSINESS_PHONE, constant.B_MOBILE);
parms.put(ConfingDetalsActivity.BUSINESS_EMAIL, constant.B_EMAIl);
parms.put(ConfingDetalsActivity.BUSINESS_PASSWORD, constant.B_PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"1");
} else {
parms.put(ConfingDetalsActivity.CONSUMER_FNAME, constant.F_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_LNAME, constant.L_NAME);
parms.put(ConfingDetalsActivity.CONSUMER_PHONE, constant.MOBILE);
constant.EMAIl);
parms.put(ConfingDetalsActivity.CONSUMER_PASSWORD, constant.PASSSOWRD);
parms.put(ConfingDetalsActivity.SIGNUP_TYPE,"0");
}
return parms;
}
};
requestQueue.add(request);
}

Volley getting an error response

I am sending some post data using volley. Here is my code . It's a snippet from background service. Let me know if you want other files also. I've added the internet permission.
public void onLocationChanged(final Location location) {
mCurrentLocation = location;
pref.setLocation(location);
String url = getResources().getString(R.string.hostname); // it's a normal http
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Location sent", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorMessage = "Err - data:"+error.getMessage();
Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put(KEY_USERID,pref.getUserId());
params.put(KEY_LAT,String.valueOf(location.getLatitude()));
params.put(KEY_LNG,String.valueOf(location.getLongitude()));
return params;
}
};
queue.add(stringRequest);
}
Actually i saw that the one of the param UserId was having the Null value, That was creating the problem

Execute a Volley request after another one is finished

I have two Volley requests. The first request authenticates the user; the second one gets data from the server.
If I send a GET request and the user is not authenticated, I want to fire the first request, authenticate the user and then keep executing the second one once the user is successfully authenticated.
So, the solution is pretty simple. :)
After I learned about callbacks and how them work, I figured out how to do that. So, I implemented a interface that declared the methods I wanted to invoke:
public interface AuthenticationCallback {
public void onLoginSuccess(String result);
public void onLoginError(String result);
}
public interface ResponseCallback {
public void onLoginSuccess(String result);
public void onAuthorizationError(String result);
}
My function:
public void getConversationMessages(final Context context, final String conversationID, final ResponseCallback responseCallback) {
final String url = GET_CONVERSATION_MESSAGES + conversationID;
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (responseCallback != null) {
responseCallback.onLoginSuccess(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error.networkResponse != null && error.networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED){
if (responseCallback != null) {
responseCallback.onAuthorizationError(error.getMessage());
}
}
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Cookie", AppSingleton.getInstance(context).getCookie());
headers.put("Content-Type", "application/json");
return headers;
}
};
AppSingleton.getInstance(context).getRequestQueue().add(stringRequest);
}
}
My Activity:
ServerConnection.getInstance().getConversationMessages(getApplicationContext(), id, new ResponseCallback() {
#Override
public void onLoginSuccess(String result) {
}
#Override
public void onAuthorizationError(String result) {
ServerConnection.getInstance().loginFunction(getApplicationContext(), userID, new AuthenticationCallback() {
#Override
public void onLoginSuccess(String result) {
ServerConnection.getInstance().getConversationMessages(getApplicationContext(), conID, new ResponseCallback() {
#Override
public void onLoginSuccess(String result) {
}
#Override
public void onAuthorizationError(String result) {
}
});
}
#Override
public void onLoginError(String result) {
}
});
}
});
Basically, the code will try to send a GETrequest. If the user is not authenticated, then it will execute the code at onAuthorizationError(), that will authenticate the user. Once the user is successfully authenticate, it will send the GET request again.
I think nesting callbacks like this is not a good practice, but I'll fix it later and update my answer.
If someone have a better way to implement that, please, post another answer!
You can put one volley method inside another, as soon as the first request gets finished it sends the another request.By doing this the data will be sent to the database and the same modified data can be fetched again. The code is as shown below.
StringRequest stringRequest = new StringRequest(Request.Method.POST, "YOUR_FIRST_URL", new Response.Listener < String > () {
#Override
public void onResponse(String response) {
StringRequest stringRequests = new StringRequest(Request.Method.POST, "YOUR_SECOND_URL", new Response.Listener < String > () {
#Override
public void onResponse(String response) {
try {
JSONArray genreArry = new JSONArray(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
return params;
}
};
int socketTimeouts = 30000;
RetryPolicy policys = new DefaultRetryPolicy(socketTimeouts, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequests.setRetryPolicy(policys);
RequestQueue requestQueues = Volley.newRequestQueue(context);
requestQueues.add(stringRequests);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map < String, String > getParams() {
Map < String, String > params = new HashMap < String, String > ();
return params;
}
};
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);

Categories

Resources