Android volley last request post call on network drop? - android

Volley works well when there is network but it goes weird when network drops.
When network is doping ie network strength is going down and i make a post request then nothing happens but once the network regain to full strength it makes the call to the previous post request not the new one?
when i clear the cache it works well...
how to solve this issue, why i am getting previous post response?
// Implements required listeners
public class VolleyServices<T> implements Response.Listener<T>, ErrorListener{
private int id; // request id
private RequestQueue request; // volley request queue
private VolleyResponce<T> listener; // callback listener
private Class<T> clazz; // parsing class
public interface VolleyResponce<T> {
public void OnSuccess(T response,int id);
public void OnError(ServerError error,int id);
}
// Constructor
public VolleyServices(VolleyResponce<T> listener,Context context) {
this.listener = listener;
request = VolleyRequest.getInstance(context).getRequestQueue();
}
// call to post the request with parse class, post parameters in map and request id
public void post(String methodName, HashMap<String, String> map,Class<T> clazz,int id) {
String url = baseUrl + methodName;
this.clazz = clazz;
this.id = id;
GsonRequest<T> myReq = new GsonRequest<T>(Request.Method.POST,url,clazz,map,this,this);
myReq.setTag(id);
request.add(myReq);
}
#Override
public void onResponse(T response) {
if(response != null && clazz == response.getClass()){
listener.OnSuccess(response,this.id);
}
}
#Override
public void onErrorResponse(VolleyError volleyError) {
ServerError error = null;
if(volleyError instanceof NetworkError) {
error = new ServerError("No internet Access, Check your internet connection.","400");
}
if(volleyError instanceof AuthFailureError) {
error = new ServerError("Authentication Failure","400");
}
if(volleyError instanceof ParseError) {
error = new ServerError("Parsing error","400");
}
if(volleyError instanceof NoConnectionError) {
error = new ServerError("No internet Access, Check your internet connection.","400");
}
if(volleyError instanceof TimeoutError) {
error = new ServerError("Request timed out, Please try again later.","400");
}
if(volleyError.networkResponse != null && volleyError.networkResponse.statusCode == 500) {
error = new ServerError("Internal server error","400");
}
else {
try {
if(volleyError.networkResponse != null) {
String responseBody = new String(volleyError.networkResponse.data, "utf-8" );
try{
Gson gson = new Gson();
error = gson.fromJson(responseBody, ServerError.class);
if(error.status == null) {
error.status = "";
}
}catch(Exception e){
e.printStackTrace();
}
} else {
error = new ServerError("Unknown Error","400");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
listener.OnError(error,this.id);
}
Some log message i captured which explains everything in detail
log link

Related

Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

I need help with my project please. I don't really have a lot to say other than that I'm trying to add payment gateway to my android app using stripe. I followed the documentation here. Towards the end where I have to test everything my app crashes and I get this error message I am almost done with this but this is the only thing in my way. Please help me. Thanks in advance
//My code is here
private void startCheckout() {
// Create a PaymentIntent by calling the sample server's /create-payment-intent endpoint.
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String json = "{"
+ "\"currency\":\"usd\","
+ "\"items\":["
+ "{\"id\":\"photo_subscription\"}"
+ "]"
+ "}";
RequestBody body = RequestBody.create(mediaType,json);
Request request = new Request.Builder()
.url(BACKEND_URL + "create-payment-intent")
.post(body)
.build();
httpClient.newCall(request)
.enqueue(new PayCallback(this));
// Hook up the pay button to the card widget and stripe instance
Button payButton = findViewById(R.id.payButton);
payButton.setOnClickListener((View view) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
if (params != null) {
ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
stripe.confirmPayment(this, confirmParams);
}
});
}
private void displayAlert(#NonNull String title,
#Nullable String message,
boolean restartDemo) {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message);
if (restartDemo) {
builder.setPositiveButton("Restart demo",
(DialogInterface dialog, int index) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
cardInputWidget.clear();
startCheckout();
});
} else {
builder.setPositiveButton("Ok", null);
}
builder.create().show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Handle the result of stripe.confirmPayment
stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(this));
}
private void onPaymentSuccess(#NonNull final Response response) throws IOException {
Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> responseMap = gson.fromJson(
Objects.requireNonNull(response.body()).string(),
type
);
// The response from the server includes the Stripe publishable key and
// PaymentIntent details.
// For added security, our sample app gets the publishable key from the server
String stripePublishableKey = responseMap.get("publishableKey");
paymentIntentClientSecret = responseMap.get("clientSecret");
// Configure the SDK with your Stripe publishable key so that it can make requests to the Stripe API
stripe = new Stripe(
getApplicationContext(),
Objects.requireNonNull(stripePublishableKey)
);
}
private static final class PayCallback implements Callback {
#NonNull private final WeakReference<PaymentPageActivity> activityRef;
PayCallback(#NonNull PaymentPageActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void onFailure(Request request, IOException e) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
activity.runOnUiThread(() ->
Toast.makeText(
activity, "Error: " + e.toString(), Toast.LENGTH_LONG
).show()
);
}
#Override
public void onResponse(Response response) throws IOException {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
if (!response.isSuccessful()) {
activity.runOnUiThread(() ->
Toast.makeText(
activity, "Error: " + response.toString(), Toast.LENGTH_LONG
).show()
);
} else {
activity.onPaymentSuccess(response);
}
}
}
private static final class PaymentResultCallback
implements ApiResultCallback<PaymentIntentResult> {
#NonNull private final WeakReference<PaymentPageActivity> activityRef;
PaymentResultCallback(#NonNull PaymentPageActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void onSuccess(#NonNull PaymentIntentResult result) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
PaymentIntent paymentIntent = result.getIntent();
PaymentIntent.Status status = paymentIntent.getStatus();
if (status == PaymentIntent.Status.Succeeded) {
// Payment completed successfully
Gson gson = new GsonBuilder().setPrettyPrinting().create();
activity.displayAlert(
"Payment completed",
gson.toJson(paymentIntent),
true
);
} else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
// Payment failed – allow retrying using a different payment method
activity.displayAlert(
"Payment failed",
Objects.requireNonNull(paymentIntent.getLastPaymentError()).getMessage(),
false
);
}
}
#Override
public void onError(#NonNull Exception e) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
// Payment request failed – allow retrying using the same payment method
activity.displayAlert("Error", e.toString(), false);
}
}
int this line
Map<String, String> responseMap = gson.fromJson(
Objects.requireNonNull(response.body()).string(),
type
);
you shold pass a json Object not a String, use GSON to fix it
something like that :
Gson g = new Gson();
Foo f = g.fromJson(jsonString, bar.class)

Getting response from server after reconnect the internet volley

While i am hitting URL to get response from server using volley ,during the fetching the net was disconnected .
my question is how to fetch data from server after reconnect the internet connection ,without hitting url once again
private void PostRequest(String Url) {
mRequest = new ServiceRequest(HomeActivity.this);
mRequest.makeServiceRequest(Url, Request.Method.GET, null, new ServiceRequest.ServiceListener() {
#Override
public void onCompleteListener(String response) {
Log.d("reponse", response);
JSONObject object = new JSONObject(response);
}
#Override
public void onErrorListener() {
indicator.setVisibility(View.GONE);
}
});
public void makeServiceRequest(final String url, int method, final
HashMap<String, String> param,ServiceListener listener) {
this.mServiceListener=listener;
stringRequest = new StringRequest(method, url, new Response.Listener<String>
() {
#Override
public void onResponse(String response) {
try {
mServiceListener.onCompleteListener(response);
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
try {
if (error instanceof TimeoutError || error instanceof
NoConnectionError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ServerError) {
} else if (error instanceof NetworkError) {
} else if (error instanceof ParseError) {
}
} catch (Exception e) {
}
mServiceListener.onErrorListener();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return param;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
return headers;
}
};
//to avoid repeat request Multiple Time
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(0, -1,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(retryPolicy);
stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
stringRequest.setShouldCache(false);
AppController.getInstance().addToRequestQueue(stringRequest);
}
}
please give suggetion,before hitting url i was checked internet connection
You can do one thing, create the collection of your failed requests. Register the broadcast receiver of CONNECTIVITY_CHANGE and WIFI_STATE_CHANGED to get notified when the internet connection is available. Once your device connects to the internet, you will get notified in registered broadcast receiver and then send retry all the request which are there in your collection. Once request is successful remove the request from the collection.
You can do with a Network Change Broadcast receiver.
Create a new class NetWorkChangeReceiver
public class NetWorkChangeReceiver extends BroadcastReceiver {
#NonNull
private final NetworkConnectionRestoredListener mListener;
public NetWorkChangeReceiver(#NonNull NetworkConnectionRestoredListener listener) {
mListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (NetworkUtil.isDeviceConnectedToInternet(context)) {
mListener.onNetworkRestored();
}
}
public interface NetworkConnectionRestoredListener {
void onNetworkRestored();
}
}
Create a NetworkUtil class
#SuppressWarnings("deprecation")
public class NetworkUtil {
private NetworkUtil() {
// no instances
}
public static boolean isDeviceConnectedToInternet(#NonNull Context context) {
ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(
CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
for (Network network : connManager.getAllNetworks()) {
if (network != null) {
final NetworkInfo networkInfo = connManager.getNetworkInfo(network);
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
}
}
return false;
} else {
NetworkInfo mWifi = connManager.getNetworkInfo(TYPE_WIFI);
if (mWifi != null && mWifi.isConnected()) {
return true;
}
NetworkInfo m3G = connManager.getNetworkInfo(TYPE_MOBILE);
if (m3G != null && m3G.isConnected()) {
return true;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
NetworkInfo mEthernet = connManager.getNetworkInfo(TYPE_ETHERNET);
return mEthernet != null && mEthernet.isConnected();
} else {
return false;
}
}
}
}
In your activity, implement NetWorkChangeReceiver.NetworkConnectionRestoredListener
public class HomeActivity extends AppCompatActivity implements NetWorkChangeReceiver.NetworkConnectionRestoredListener {
NetWorkChangeReceiver mNetworkChangeReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
//Use this to register the receiver while making the server call.
context.registerReceiver(mNetworkChangeReceiver = new NetWorkChangeReceiver(this), new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
public void onNetworkRestored() {
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
if (mNetworkChangeReceiver != null) {
try {
unregisterReceiver(mNetworkChangeReceiver);
mNetworkChangeReceiver = null;
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
#Override
protected void onStop() {
super.onStop();
if (mNetworkChangeReceiver != null) {
try {
unregisterReceiver(mNetworkChangeReceiver);
mNetworkChangeReceiver = null;
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
}

Retrofit - how do I make a synchronous request within an asynchronous request

I'm implementing a two-level nested recyclerView and both recycler views make an API call using retrofit. This is the method that makes the synchronous request:
public void loadSectionStories(String sessionKey, CuratedSection section) {
Call<JsonArray> subCall;
subCall = TravelersApi.endpoint().getCuratedSectionTopics(sessionKey, section.id);
try {
Response<JsonArray> response = subCall.execute();
if(response.code() != 200) {
Toast.makeText(getApplicationContext(), "Cannot load page as of the moment.", Toast.LENGTH_SHORT).show();
return;
}
JsonArray rawStories = response.body();
if(rawStories.size() == 0) {
//TODO: show placeholder
return;
}
ArrayList<CuratedSectionItem> stories = new ArrayList<>();
for(int i = 0; i < rawStories.size(); i++) {
JsonObject jStories = rawStories.get(i).getAsJsonObject();
JSONObject temp = new JSONObject(jStories.toString());
JsonObject author = jStories.get("author").getAsJsonObject();
CuratedSectionItem story = new CuratedSectionItem();
story.title = jStories.get("title").getAsString();
story.avatar = author.get("profile_photo").getAsString();
story.displayPhoto = temp.getString("primary_photo");
story.username = author.get("username").getAsString();
story.description = jStories.get("content").getAsString();
story.topicId = jStories.get("id").getAsString();
story.postId = jStories.get("first_post_id").getAsString();
story.hasReacted = false;
story.upvotes = jStories.get("stats").getAsJsonObject().get("upvotes").getAsInt();
stories.add(story);
}
section.stories = stories;
} catch (IOException e) {
Log.d("ERROR!", e.toString());
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
This is the method that makes the asynchronous request and also calls loadSectionStories in a thread:
public void loadCuratedSections(final int start, final int limit) {
SharedPreferences prefs = getSharedPreferences("user_session", MODE_PRIVATE);
final String sessionKey = prefs.getString("session_key", null);
Call<JsonArray> call;
call = TravelersApi.endpoint().getCuratedSections(sessionKey);
call.enqueue(new Callback<JsonArray>() {
#Override
public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {
if(response.code() != 200) {
Toast.makeText(getApplicationContext(), "Cannot load page as of the moment.", Toast.LENGTH_SHORT).show();
return;
}
JsonArray rawSections = response.body();
if(rawSections.size() == 0) {
return;
}
for (int i = start; i < limit; i++) {
JsonObject jSection = rawSections.get(i).getAsJsonObject();
final CuratedSection section = new CuratedSection();
section.id = jSection.get("id").getAsString();
section.header = jSection.get("section_header").getAsString();
section.isShown = jSection.get("is_shown").getAsBoolean();
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
loadSectionStories(sessionKey, section);
}
});
thread.start();
curatedSections.add(section);
}
}
#Override
public void onFailure(Call<JsonArray> call, Throwable t) {
Log.d("ERROR!", t.toString());
t.printStackTrace();
}
});
}
Everything is working fine except the fact that section.stories returns null. It doesn't make sense to me because of this statement section.stories = stories inside loadSectionStories.
If you are using section.stories before your synchronous request is completed (which is running in new threads) then it will return null which is currently happening.
so either you have to remove new thread flow if you want to use it after your first asynchronous request is completed,
or you have to reload your recycler view when you stories is updated.
Also why are you executing your synchronous request(loadSectionStories) in new thread, is it not similar to asynchronous request?
Retrofit asyncRetrofit = new Retrofit.Builder()
.baseUrl(URLS.MAIN_SERVER_URL)
// below line create thread for syncrouns request
.callbackExecutor(Executors.newSingleThreadExecutor())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
this will run your request in asyncronous

Volley second request return null

The first request done successfully but second request in queue return null , when setting break point and start debugging the second request get it's value successfully
class ListLoader extends AsyncTask<Void,Void,MerchantCategories[]>
{
MerchantCategories[] data;
protected void onPreExecute() {
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected MerchantCategories[] doInBackground(Void... params) {
Gson g = new Gson();
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
try {
regid = gcm.register(PROJECT_NUMBER);
String msg="";
msg = "Device registered, registration ID=" + regid;
Log.i("GCM", msg);
EgxServices.getJsonFrom("http://inareg.com/APIs/RegisterAndroidDevice?registrationID="+regid,(Activity) c);
} catch (IOException e) {
e.printStackTrace();
}
MerchantCategories[] categs=g.fromJson(EgxServices.getJsonFrom("http://inareg.com/APIs/ListMerchantCategories",(Activity) c),MerchantCategories[].class);
return categs;
}
protected void onPostExecute(MerchantCategories[] response) {
if(response == null) {
progressBar.setVisibility(View.GONE);
}
else{
progressBar.setVisibility(View.GONE);
MerchantCategoriesAdp adp =new MerchantCategoriesAdp(c,R.layout.lst_merchant_categories,response);
drawerList.setAdapter(adp);
// Log.i("INFO", response);
// responseView.setText(response);
}
}
}
This method which i used to initialize a new request and return JSON String
public static String getJsonFrom(final String urlStr, Activity context) {
final Context c = context;
final SharedValue value = new SharedValue();
String result="";
StringRequest request = new StringRequest(Request.Method.GET,urlStr,new Response.Listener<String>(){
#Override
public void onResponse(String response) {
value.setResult(response);
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(c, "No Internet Connection",
Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(c).add(request);
return value.getResult();
}
as you can see that first request
EgxServices.getJsonFrom("http://inareg.com/APIs/RegisterAndroidDevice?registrationID="+regid,(Activity) c);
run successfully but the second one ,
EgxServices.getJsonFrom("http://inareg.com/APIs/ListMerchantCategories",(Activity) c);
always return null value ...
i need to know why ?????!!!
Try this :
request.setShouldCache(false);
before Volley.newRequestQueue(c).add(request);

Android Volley Request Identity onErrorResponse Section

public void getTestDats(String unique_id) {
final String tag = "testList";
String url = Constants.BASE_URL + "test_module.php";
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1"));
params.put("unique_id", unique_id);//1,2,3,4,5
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
switch (response.optInt("unique_id")) {
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//I want to know which unique_id request is failed
}
});
loginRequest.setRetryPolicy(new DefaultRetryPolicy(20000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(loginRequest, tag);
}
I'm trying to identity which request is failed with having unique_id.
I'm calling getTestDats("1") function with unique_id. And function called 10 times and all the api call in addToRequestQueue.
When API go into Success part its working as per code.
But when API go into Error part I didn't identity the request.
Is there any way to know my request param so I can retry with particular unique_id request.
set a field in loginRequest and in onErrorResponse access the field like loginRequest.getUniqueId()
Alternatively, create a seperate class that implements Response.Listener and ErrorListener
Response Listener class:
public class MyReponseListener implements Response.Listener<JSONOBject>{
private long uniqId;
public MyResponseListener(long uniqId){
this.uniqId = uniqId;
}
#Override
public void onResponse(JSONObject response) {
System.out.println("response for uniqId " + uniqId);
// do your other chit chat
}
}
ErrorListener class:
public class MyErrorListener implements ErrorListener{
private long uniqId;
public MyErrorListener(long uniqId){
this.uniqId = uniqId;
}
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("Error for uniqId : " + uniqId);
}
}
Now call it like:
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new MyResponeListener(uniqId), new MyErrorListener(uniqId));
Now if you want some code of the calling class to be accessible in the ErrorListener class then do the following:
1. In calling class put the codes you want to access in methods
2. Create an interface with those method
3. The calling class will implement that interface
4. Pass the interface to constructor of the MyErrorListener or MyResponseListener
for example an activity calls the volley request, on error you want to show a message.
put that show error codes in a method:
public void showMessage(int errorCode){
//message according to code
}
now create an interface
public interface errorMessageInterface{
void showMessage(int errorCode);
}
the activity will implement errorMessageInterface and pass this to the constructor of MyErrorListener and save it in a field.
Inside onErrorResponse, you will call
field.showMessage()
You can parse error response in the same way as you parse success response. I use similar solution in my projects.
public class VolleyErrorParser {
private VolleyError mError;
private String mBody;
private int mUniqueId = -1;
public VolleyErrorParser(VolleyError e){
mError = e;
parseAnswer();
parseBody();
}
private void parseBody() {
if (mBody==null)
return;
try{
JSONObject response = new JSONObject(mBody);
mUniqueId = response.getOptInt("unique_id");
}catch (JSONException e){
e.printStackTrace();
}
}
private void parseAnswer() {
if (mError!=null&&mError.networkResponse!=null&&mError.networkResponse.data!=null){
mBody = new String(mError.networkResponse.data);
}
}
public String getBody(){
return mBody;
}
public int getUniqueId(){
return mUniqueId;
}
}
Use:
...
, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int id = new VolleyErrorParse(error).getUniqueId();
switch (id) {
case -1:
//unique id not found in the answer
break;
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
}
...
Just add this code to identify which type of error you are facing.Add this in your onError() method :
if (error instanceof TimeoutError) {
Log.e(TAG, "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e(TAG,"tNoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e(TAG,"AuthFailureError");
} else if (error instanceof ServerError) {
Log.e(TAG,"ServerError");
} else if (error instanceof NetworkError) {
Log.e(TAG,"NetworkError");
} else if (error instanceof ParseError) {
Log.e(TAG,"ParseError");
}
Log the unique_id before making a request i.e; after params.put("unique_id", unique_id);//1,2,3,4,5. And also once you get the response in onResponse() method. And cross verify what exactly is happening.
most of the solutions here will "work" but they are too complex .. for me :)
here is the simplest option with least code change I can think of:
...
final Map<String, String> params = new HashMap<String, String>();
params.put("user_id", SharedPreferenceUtil.getString(Constants.PrefKeys.PREF_USER_ID, "1"));
params.put("unique_id", unique_id);//1,2,3,4,5
DataRequest loginRequest = new DataRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
switch (params.get("unique_id")) {
case 1:
//task 1
break;
case 2:
//task 2
break;
default:
//nothing
}
}
...
All the above answers seem to be correct.But i recommend you to do this in an optimized way. If you will add error handling code in all onErrorResponse() then it will create duplication. So create a seperate method in Utils or some other class and just call that method by passing error object to the method. Also you can inflate some dialog or toast to display an error message.
public static void handleError(final Context context, String alertTitle,
Exception exception, String logTag) {
if (context != null) {
if (exception instanceof TimeoutError)
message = context.getString(R.string.TimeoutError);
else if (exception instanceof NoConnectionError)
message = context.getString(R.string.NoConnectionError);
else if (exception instanceof AuthFailureError)
message = context.getString(R.string.AuthFailureError);
else if (exception instanceof ServerError)
message = context.getString(R.string.ServerError);
else if (exception instanceof NetworkError)
message = context.getString(R.string.NetworkError);
else if (exception instanceof ParseError)
message = context.getString(R.string.ParseError);
message = exception.getMessage();
DialogHelper.showCustomAlertDialog(context, null,
alertTitle, message, "ok",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
}, null, null);
}
}
I think you have to make one conman method on Base class. As given bellow which I used in my code for calling php web api
/**
* <h1> Use for calling volley webService </h1>
*
* #param cContext Context of activity from where you call the webService
* #param mMethodType Should be POST or GET
* #param mMethodname Name of the method you want to call
* #param URL Url of your webService
* #param mMap Key Values pairs
* #param initialTimeoutMs Timeout of webService in milliseconds
* #param shouldCache Web Api response are stored in catch(true) or not(false)
* #param maxNumRetries maximum number in integer for retries to execute webService
* #param isCancelable set true if you set cancel progressDialog by user event
* #param aActivity pass your activity object
*/
public void callVolley(final Context cContext, String mMethodType, final String mMethodname, String URL,
final HashMap<String, String> mMap, int initialTimeoutMs, boolean shouldCache, int maxNumRetries,
Boolean isProgressDailogEnable, Boolean isCancelable, final Activity aActivity) {
mMap.put("version_key_android",BuildConfig.VERSION_NAME+"");
if (!isOnline(cContext)) {
//showErrorDailog(aActivity, Constant.PleaseCheckInternetConnection, R.drawable.icon);
} else {
StringRequest jsObjRequest;
int reqType = 0;
String RequestURL = URL.trim();
queue = Volley.newRequestQueue(cContext);
if (isProgressDailogEnable) {
customLoaderDialog = new CustomLoaderDialog(cContext);
customLoaderDialog.show(isCancelable);
customLoaderDialog.dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// finish();
}
});
}
if (mMethodType.trim().equalsIgnoreCase("GET"))
reqType = com.android.volley.Request.Method.GET;
else if (mMethodType.trim().equalsIgnoreCase("POST"))
reqType = com.android.volley.Request.Method.POST;
if (RequestURL.equals(""))
RequestURL = Constant.BASE_URL;
else
RequestURL = URL;
if (Constant.d) Log.d("reqType", reqType + "");
jsObjRequest = new StringRequest(reqType, RequestURL, new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (Constant.d) Log.d("response==>" + mMethodname, "" + response);
if (customLoaderDialog != null) {
try {
customLoaderDialog.hide();
} catch (Exception e) {
e.printStackTrace();
}
}
if (response == null || response.length() == 0) {
IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
iVolleyRespose.onVolleyResponse(404, response, mMethodname);
} else {
JSONObject json_str;
try {
json_str = new JSONObject(response);
int status = json_str.getInt("status");
if (status == 100) {
AlertDialog alertDialog = new AlertDialog.Builder(aActivity).create();
alertDialog.setTitle(getResources().getString(R.string.app_name));
alertDialog.setMessage(json_str.getString("message") + "");
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse(Constant.playStoreUrl));
startActivity(viewIntent);
}catch(Exception e) {
Toast.makeText(getApplicationContext(),"Unable to Connect Try Again...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
// return;
}
});
alertDialog.show();
} else {
IVolleyRespose iVolleyRespose = (IVolleyRespose) aActivity;
iVolleyRespose.onVolleyResponse(RESPONSE_OK, response, mMethodname);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
IVolleyRespose iVolleyError = (IVolleyRespose) aActivity;
iVolleyError.onVolleyError(404, "Error", mMethodname);
if (customLoaderDialog != null) {
customLoaderDialog.hide();
}
}
}) {
#Override
protected Map<String, String> getParams() {
String strRequest = "";
try {
strRequest = getWebservicejsObjRequestforvolley(mMethodname, mMap);
if (Constant.d) Log.d("Request==>", strRequest + "");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, String> params = new HashMap<>();
params.put("json", strRequest);
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
//if(Constant.d) Log.d("Request==>", jsObjRequest+"");
jsObjRequest.setTag(mMethodname);
jsObjRequest.setShouldCache(shouldCache);
jsObjRequest.setRetryPolicy(new DefaultRetryPolicy(initialTimeoutMs, maxNumRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(jsObjRequest);
}
}
Please observe that here we make one interface for getting response and error.
Using Interface you can get method name on both response and error so you can identify which web api is successfully called and which give error. You should extend base class to Activity and also implement Interface which you made for getting volley response. Here in above code I show how to bind interface to activity. when you call api by passing activity context.

Categories

Resources