I have a serious problem.
I have a small app for a restaurant to manage the creation of orders, update, and so. Waiters use an android tablet to serve to the customers.
The thing is that since a week or so, I realized that tickets tend to duplicate items. After some research and diving into the logs, I realized that many times, when I call an AsyncTask to make a request to the server, it doesn't send ONE request, it sends several requests instead.
For that reason, if I call the "addItemToOrder" service four times, it will add four items instead of just one.
Here is my code. This is a "generic GET Async Task" that I call. It has an url, it may or not has some parameters, and it just creates a volley request that sends to the server. As you can see, it has 0 retries and, before you can ask, I just made sure that this AT is not being called more than once:
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.FunctionsHelper;
abstract class GenericGetAsyncTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "DEBUG GenericGetAT";
Handler h;
WeakReference<Context> context;
String auxURL;
HashMap<String, String> postParams;
String query;
GenericGetAsyncTask(WeakReference<Context> context, Handler h) {
this.auxURL = "";
this.context = context;
this.h = h;
this.postParams = new HashMap<>();
this.query = "";
}
#Override
protected Void doInBackground(final Void... params) {
if (!FunctionsHelper.isConnected(context.get())) {
h.sendEmptyMessage(ErrorHelper.HANDLER_NO_INTERNET_ERROR);
Bugfender.d(TAG, "No internet connection");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_NO_INTERNET_ERROR, TAG);
return null;
}
String urlParcial = Constants.getUrl(context.get());
if (urlParcial.equals("")) {
h.sendEmptyMessage(ErrorHelper.HANDLER_FALTA_URL);
Bugfender.d(TAG, "Falta url");
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_URL_INCORRECTA, TAG);
return null;
}
int metodo;
String url;
if (query == null || query.equals("")) {
url = urlParcial + this.auxURL;
metodo = Request.Method.POST;
} else {
url = urlParcial + this.auxURL + "?" + this.query;
metodo = Request.Method.GET;
}
Bugfender.d(TAG, "url -> " + url);
final RequestQueue queue = Volley.newRequestQueue(context.get());
final StringRequest request = new StringRequest(metodo, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
onResultRetrieved(response);
} catch (JSONException e) {
Bugfender.d(TAG, "Hubo un error de json en onResponse -> " + e.toString());
h.sendEmptyMessage(ErrorHelper.HANDLER_RESPUESTA_INCORRECTA);
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_JSON, TAG);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Bugfender.d(TAG, "Error recibido del servidor -> " + error.toString());
ErrorHelper.mostrarError(context.get(), ErrorHelper.HANDLER_RESPUESTA_INCORRECTA, TAG);
Toast.makeText(context.get(), "Error realizando llamada http -> " + error.toString(), Toast.LENGTH_SHORT).show();
h.sendEmptyMessage(ErrorHelper.HANDLER_ERROR);
}
}) {
#Override
protected Map<String, String> getParams() {
return postParams;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(2000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
return null;
}
protected abstract void onResultRetrieved(String result) throws JSONException;
}
After that, then I just have to inherit from this generic AT with just some bit of code to make a simple request, just as you can see here in this "UpdateTicketAT":
package es.vdevelop.tpvmobile.asynctask;
import android.content.Context;
import android.os.Handler;
import com.bugfender.sdk.Bugfender;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import es.vdevelop.tpvmobile.Constants;
import es.vdevelop.tpvmobile.ErrorHelper;
import es.vdevelop.tpvmobile.Functions;
public class UpdateTicketAsyncTask extends GenericGetAsyncTask {
private static final String TAG = "DEBUG UpdateTicketAT";
public UpdateTicketAsyncTask(WeakReference<Context> context, Handler h, String json) {
super(context, h);
this.auxURL = "actualizar_ticket.php";
this.postParams.put("ticket", json);
Bugfender.d(TAG, "Ticket que vamos a enviar -> " + json);
}
#Override
protected void onResultRetrieved(String response) throws JSONException {
Bugfender.d(TAG, "Respuesta obtenida del servidor -> " + response);
JSONObject result = new JSONObject(response);
int codigo = result.getInt("codigo");
if (codigo == 0) {
h.sendEmptyMessage(Constants.handlerOk);
Bugfender.d(TAG, "Ticket actualizado correctamente");
} else {
h.sendEmptyMessage(Constants.handlerError);
ErrorHelper.mostrarError(context.get(), codigo, TAG);
}
}
}
I can't find out what is happening here. Am I doing something wrong?
One important thing is that the calls to the server may not be all made in a row. I mean, I make a request, I get the response, and maybe a minute or two later, the request is made again!
I just can be aware of this by looking into the server logs..
I don't know what's happening here..
Anyway, thanks in advance!
I can see two ways to answer your question or not:
First: i don`t like your "0" in your DefaultRetryPolicy line, try to put some like this:
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
The first parameter is timeout, second is max retries (yes i know, you know that but check that is 1) and the last one is DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ( again i know, blah blah, but check that is 1.0f) or put literal.
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_SERVICE,
1, 1.0f));
Second: Can you only set more time in your time out.
I hope this help you.
Related
I want to get the results about imei adresses after my inquiry on the inquiry site. The site has token input during the query and I can get this token as follows. But when i run the second volley queue i soppose the token changes and the result doesn't come. How can I solve this problem. The site that i questioned the imei adress and my codes are below.
package com.myapp.query;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import android.os.Bundle;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import androidx.appcompat.app.AppCompatActivity;
public class imeiSorgulama extends AppCompatActivity {
StringRequest stringRequest;
RequestQueue queue;
String token, tag, value, tag2, value2, result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_imei_sorgulama);
queue = Volley.newRequestQueue(this);
final String url = "https://www.turkiye.gov.tr/imei-sorgulama";
stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tag = "<input type=\"hidden\" name=\"token\" value=\"";
value = response.substring(response.indexOf(tag) + tag.length());
token = value.substring(0, value.indexOf("\""));
try {
token = URLEncoder.encode(token,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
imeiQuery();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
);
queue.add(stringRequest);
}
private void imeiQuery() {
final String url = "https://www.turkiye.gov.tr/imei-sorgulama?submit";
stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
tag2 = "<dl class=\"compact\">";
value2 = response.substring(response.indexOf(tag2) + tag2.length());
result = value2.substring(0, value2.indexOf("</dl>"));
Toast.makeText(imeiSorgulama.this, result+"", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(imeiSorgulama.this, error+"", Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("txtImei", "545454545454545");
params.put("token=", token);
return params;
}
};
queue.add(stringRequest);
}
}
There are libraries available for login with outlook using a browser (especially chrome browser i.e. MSAL android library ) OR ADAL, but I don't want to log-in with chrome because in my device chrome is not available (Its custom OS flashed in an android device).
I have tried on my end also but its not working as this code is giving access token but not useful to call graph API
here is my code
package learn2crack.weboauth2;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity implements View.OnClickListener {
private static final String TAG = "MainActivity";
//Change the Scope as you need
WebView web;
Button auth;
SharedPreferences pref;
TextView Access;
String authCode = "";
private Dialog auth_dialog;
private Button authEbay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = getSharedPreferences("AppPref", MODE_PRIVATE);
Access =(TextView)findViewById(R.id.Access);
auth = (Button)findViewById(R.id.auth);
auth.setOnClickListener(this);
authEbay = (Button)findViewById(R.id.auth_ebay);
auth.setOnClickListener(this);
authEbay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.auth:
auth(Constants.OUTLOOK.USER_AGENT,
Constants.OUTLOOK.OAUTH_URL,
Constants.OUTLOOK.REDIRECT_URI,
Constants.OUTLOOK.CLIENT_ID,
Constants.OUTLOOK.OAUTH_SCOPE);
break;
case R.id.auth_ebay:
auth(Constants.EBAY.USER_AGENT,
Constants.EBAY.OAUTH_URL,
Constants.EBAY.REDIRECT_URI,
Constants.EBAY.CLIENT_ID,
Constants.EBAY.OAUTH_SCOPE);
break;
}
}
private void auth(String userAgent, String oauthUrl, String redirectUri, String clientId,
String oauthScope) {
final Dialog auth_dialog;
// TODO Auto-generated method stub
auth_dialog = new Dialog(MainActivity.this);
auth_dialog.setContentView(R.layout.auth_dialog);
web = (WebView)auth_dialog.findViewById(R.id.webv);
web.getSettings().setJavaScriptEnabled(true);
WebSettings webSettings = web.getSettings();
web.getSettings().setUserAgentString(userAgent);
webSettings.setSupportMultipleWindows(true);
web.loadUrl(oauthUrl+"?redirect_uri="+
redirectUri+"&response_type=code&client_id="+
clientId+"&scope="+ oauthScope);
web.setWebViewClient(new WebViewClient() {
boolean authComplete = false;
Intent resultIntent = new Intent();
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.contains("?code=") && authComplete != true) {
Uri uri = Uri.parse(url);
authCode = uri.getQueryParameter("code");
callGraphAPI(authCode);
Log.i("", "CODE : " + authCode);
authComplete = true;
resultIntent.putExtra("code", authCode);
auth_dialog.dismiss();
Toast.makeText(getApplicationContext(),"Authorization Code is: "
+authCode, Toast.LENGTH_SHORT).show();
}else if(url.contains("error=access_denied")){
Log.i("", "ACCESS_DENIED_HERE");
Toast.makeText(getApplicationContext(), "Error Occured",
Toast.LENGTH_SHORT).show();
auth_dialog.dismiss();
}
}
});
auth_dialog.show();
auth_dialog.setTitle("Authorize Learn2Crack");
auth_dialog.setCancelable(true);
}
private void callGraphAPI(final String code)
{
Log.d(TAG, "Starting volley request to graph");
/* Make sure we have a token to send to graph */
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject parameters = new JSONObject();
try {
parameters.put("key", "value");
} catch (Exception e) {
Log.d(TAG, "Failed to put parameters: " + e.toString());
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Constants.OUTLOOK.MSGRAPH_URL,
parameters,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
/* Successfully called graph, process data and send to UI */
Log.d(TAG, "Response: " + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap();
headers.put("Authorization", "Bearer " + authCode);
return headers;
}
};
Log.d(TAG, "Adding HTTP GET to Queue, Request: " + request.toString());
request.setRetryPolicy(new DefaultRetryPolicy(
3000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}
}
anybody please suggeest how to get proper access token after login with microsoft/outlook using webview.
Thanks in advance.
How can we pass params from editText to url using request.GET method.
Actually I am trying to pass an email address as parameter to a api which should b attached to api-url .
I came to know from here that getParams() is not called on the GET method, so it seems you'll have to add it to the URL before you send the request.
suggest me any solution to achieve the task ..
when i pass REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
it return success=true response as expected because is registered user
but if i set REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser and pass the params (get value from edittext and use params.put in getparams() method ).response is always success=false i.e params is not attached to url
here is my code.
package com.example.mts3.hammadnewsapp;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class RegisterActivity extends AppCompatActivity {
Button btn_verf;
EditText et_Email;
String u_emails,stat;
AlertDialog.Builder alertDialog;
private static final String TAG = "LoginActivity";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;
// public static String firstname, lastname, useremail, userphone, userpass;
// String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser?email=ameer#novatoresols.com";
String REG_URL="http://ec2-54-147-238-136.compute-1.amazonaws.com/hmc/api/registeruser";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
btn_verf=findViewById(R.id.btn_reg_send_vf_code);
et_Email=findViewById(R.id.et_reg_email);
alertDialog =new AlertDialog.Builder(RegisterActivity.this);
// u_emails=et_Email.getText().toString().trim();
btn_verf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callApi();
}
});
}
private void callApi() {
// Log.e(TAG, "onClick: ");
/*if (!utility.isInternetConnected()) {
Toast.makeText(LoginActivity.this, "Please check your internet connection.", Toast.LENGTH_SHORT).show();
return;
}*/
// dialog = utility.showProgressDialog(LoginActivity.this, "Please wait");
final String email = et_Email.getText().toString().trim();
// Log.e(TAG, "onClick: email = " + email );
// JSONObject params = new JSONObject();
/*
HashMap<String,String> params=new HashMap<>();
params.put("email",email);*/
/*try {
// params.getString("email");
params.put("email",email);
Log.e(TAG, "getParams: param = " + "try of put prams");
} catch (JSONException e){
Log.e(TAG, "getParams: param = " + "catch of put prams");
e.printStackTrace();
}*/
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, REG_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(RegisterActivity.this, "REsponse: " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params=new HashMap<>();
// params.put("email",email);
params.put("email",email);
return params;
}
}; queue.add(stringRequest);
}
}
As suggested by #Puneet worked for me which is as :
getParams is only called for POST requests. GET requests don't have a body and hence, getParams is never called. For a simple request like yours just add the parameters to your URL and use that constructed URL to make that request to your server (REG_URL + "?email=" + email).
To pass the parameters, you need to create a class for the key-value pairs.
1) Create a class KeyValuePair with two fields key and value with appropriate constructor and getter-setter methods.
2) Now, for each parameter, you need to create an object of this class, i.e., for a key username with value user#gmail.com, the object would be new KeyValuePair("username", "user#gmail.com").
3) Now, you need to create a List to store these parameters and pass this list to the below method with your base url,
public static String generateUrl(String baseUrl, List<KeyValuePair> params) {
if (params.size() > 0) {
for (KeyValuePair parameter: params) {
if (parameter.getKey().trim().length() > 0)
baseUrl += "&" + parameter.getKey() + "=" + parameter.getValue();
}
}
return baseUrl;
}
4) Pass this baseUrl to your Request.
I know there are enormous library or API used with android HTTP Get,Post,Put.But can somebody tell me which library are better for get post and put and other various library
If you want to make requests to a database from your app, I recommand you to use the Google's library made for it : Volley
You can find tutorials like this one which will permit you to make POST or GET requests.
You can also consult the documentation of Google on volley
There are mostly tow library used with network relate operation like send receive data or request,response e.t.c,
1) volley
2) Retrofit
Both are good library and both are flexible and manageable library.
For Retrofit Click Here
For volley Click Here
You should use volley, it is the best thing out there, here I'm uploading some code to help you out.
ApplicationController.java
You have to add this file in manifest file's application tag,
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.Volley;
public class ApplicationController extends Application {
public static final String TAG = "VolleyPatterns";
private static ApplicationController sInstance;
private RequestQueue mRequestQueue;
public static synchronized ApplicationController getInstance() {
return sInstance;
}
#Override
public void onCreate() {
super.onCreate();
sInstance = this;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
req.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
VolleyLog.d("Adding request to queue: %s", req.getUrl());
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
req.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
));
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
CustomRequest.java
Custom request to connect to database and get data.
import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import raghav.bookthat.support.Constants;
public class CustomRequest {
static final String[] response = new String[1];
private StringRequestCompleteListener stringRequestCompleteListener;
public CustomRequest(StringRequestCompleteListener stringRequestCompleteListener) {
this.stringRequestCompleteListener = stringRequestCompleteListener;
}
public static String getResponse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("Error").equals("200")) {
return jsonObject.getString("response");
} else {
return null;
}
}
public void loadJSON(final HashMap<String, String> headers, final Context context, final ProgressDialog progressDialog) {
if (headers != null) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.WEBSERVICE, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
try {
response[0] = getResponse(s);
if (stringRequestCompleteListener != null && response[0] != null) {
stringRequestCompleteListener.onTaskCompleted(response[0]);
} else {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
} catch (JSONException e) {
if (progressDialog != null) {
progressDialog.dismiss();
}
response[0] = null;
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError) {
Toast.makeText(context, "Please Wait\n The Internet is Quite Slow Down Here", Toast.LENGTH_SHORT).show();
loadJSON(headers, context, progressDialog);
} else {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
return headers;
}
#Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
ApplicationController.getInstance().addToRequestQueue(stringRequest);
}
}
}
StringRequestCompleteListener.java
Listener to handle response of volley
public interface StringRequestCompleteListener {
void onTaskCompleted(String response);
}
Use of custom request
HashMap<String, String> headers = new HashMap<>();
headers.put("method", "createBooking");
headers.put("PackageID", String.valueOf(bundle.getInt("PackageID")));
headers.put("UserID", String.valueOf(sharedPreferencesHelper.getUserID()));
headers.put("Price", txtTotalPrice.getText().toString());
headers.put("TotalPerson", edTotalPerson.getText().toString());
headers.put("BookingStartDateTime", txtStartDateTime.getText().toString());
headers.put("BookingEndDateTime", txtEndDateTime.getText().toString());
final ProgressDialog progress = SupportMethods.showProgressDialog(context);
progress.show();
new CustomRequest(new StringRequestCompleteListener() {
#Override
public void onTaskCompleted(String response) {
progress.dismiss();
if (response.equals("800")) {
Toast.makeText(context, "Location Already Booked On Given Time, \n Please Select Any Other Time Or Location", Toast.LENGTH_LONG).show();
} else if (response.equals("400")) {
Toast.makeText(context, "Error Occurred While Booking, Please Try Again", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Location Booked Successfully", Toast.LENGTH_LONG).show();
startActivity(new Intent(context, ActivityDrawer.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
startService(new Intent(context, BackgroundUpdateService.class).putExtra(Constants.UPDATE,Constants.BOOKING_UPDATE));
}
}
}).loadJSON(headers, context, progress);
AndroidManifest.xml
add this permission
<uses-permission android:name="android.permission.INTERNET" />
add ApplicationController to Application Tag
<application
android:name=".support.volley.ApplicationController"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:supportsRtl="true"
android:theme="#style/AppTheme"><application>
You used this for Http..
httpclient-4.2.3.jar Download Link For Httpclient-4.2.3.jar
apache-httpcomponents-httpcore.jar Download Link for apche-httpcomponents
I want to make a library to reduce my duplicate network works on every android projects or even give my jar to some other developers to using my methods for network communications.
So i build this:
import java.util.Map;
import org.json.JSONObject;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
public class RequestResp {
private final static String WEB_SERVICE_URL = "http://blabla/api";
private final Priority priorityImmediatelly = Priority.IMMEDIATE;
private final Priority priorityHigh = Priority.HIGH;
private final Priority priorityNORMAL = Priority.NORMAL;
private String tag_req_default = "tag_req_default";
VolleyCustomRequest mVolleyCustomReq;
DefaultRetryPolicy drp = new DefaultRetryPolicy(15000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
public /*JSONObject*/ void sendParamsAsHighPriority(Map<String, String> params) {
mVolleyCustomReq = new VolleyCustomRequest(Method.POST,
WEB_SERVICE_URL, params, new Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
}
}
}, new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag_req_default, error.getMessage());
}
}) {
#Override
public Priority getPriority() {
return priorityHigh;
}
};
mVolleyCustomReq.setRetryPolicy(drp);
VolleyController.getInstance().addToRequestQueue(mVolleyCustomReq,
tag_req_default);
/*return response; ?!?!?*/
}
}
But how to return response?! Cause if server was busy or down or something that make response a little late, developers in their applications get null!(i guess).
How to make a such this?! Build a jar library that has a class that has a method that give parameters and send it on specific URL, with volley library?
Define Interface like
public interface OntaskCompleted {
public void onSuccess(JSONObject response);
public void onError(String message);
}
Now Your activity should implement this interface and you have to override these method.
Now in you Volley class do this.
if (response != null) {
ontaskCompleted.onSuccess(JSONObject);
}
and
public void onErrorResponse(VolleyError error) {
VolleyLog.d(tag_req_default, error.getMessage());
ontaskCompleted.onError( error.getMessage());
}
Now your activity will get the result of error or success.
Hope it helps you.