Confused about which Library.... to use - android

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

Related

Android volley token changes every request

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

Volley perform too many uncontrolled retries

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.

app crashes when try to create new record on remote database mysql using volley

I have created a simple android app which connect to Remote sql database.. the problem is when I click on register the application crash. please help me guys
package com.example.akshay.webservices;
/**
* Created by Akshay on 7/20/2015.
*/
import com.example.akshay.webservices.AppConfig;
import com.example.akshay.webservices.AppController;
import com.example.akshay.webservices.SQLiteHandler;
import com.example.akshay.webservices.SessionManager;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
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.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AppController.java
package com.example.akshay.webservices;
import android.app.Application;
/**
* Created by Akshay on 7/19/2015.
*/
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
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);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
LogCat:
07-20 20:27:07.195 8233-8233/? E/Zygote﹕ MountEmulatedStorage()
07-20 20:27:07.195 8233-8233/? E/Zygote﹕ v2
07-20 20:27:07.195 8233-8233/? E/SELinux﹕ [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
07-20 20:27:18.355 8233-8233/com.example.akshay.webservices E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.akshay.webservices, PID: 8233
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.akshay.webservices.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
at com.example.akshay.webservices.RegisterActivity.registerUser(RegisterActivity.java:185)
at com.example.akshay.webservices.RegisterActivity.access$300(RegisterActivity.java:32)
at com.example.akshay.webservices.RegisterActivity$1.onClick(RegisterActivity.java:81)
at android.view.View.performClick(View.java:5191)
at android.view.View$PerformClick.run(View.java:20916)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5972)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
This is the logcat I am unable to understand what is happening. Please help..
Problem is happening cause AppController.getInstance() it's returning null,
you have to change your AppController.getInstance() method to be this way:
public static AppController getInstance() {
if (mInstance == null) {
mInstance = new AppController;
}
return mInstance;
}
also make sure that you are registering your app class in your manifest
you should have an attribute in your manifest app like this:
<application
android:name="package.AppController" <--------
android:allowBackup="true"
android:debuggable="true"
android:icon="#drawable/ic_launcher"
android:label="xyz"
android:screenOrientation="landscape"
android:theme="#style/AppTheme">
More info here: http://developer.android.com/reference/android/app/Application.html
"Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created. "
Hey i had the same issue and when i tried this solution it did not work finally i got a way out.
The problem why it is returning a null pointer is because the methods getInstance() and getRequestQueue() are returning nothing with respect to the context. To solve that follow this steps. As prerequisite ad the following global variable in under public class AppController extends Application private Context myContext.
STEP 1.
Create a constructor that defines the context
public AppController(Context context){
myContext = context;
mRequestQueue = getRequestQueue();
}
STEP 2. Modify hyou getInstance() method to work within the context as follow:
public static synchronized AppController getInstance(Context context) {
if(mInstance==null){
mInstance = new AppController(context);
}
return mInstance;
}
Step 3.
Finally modify the getRequestQueue() method to work within the context as follows
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(myContext.getApplicationContext());
}
return mRequestQueue;
}
Finally got the calling class and call the methods from AppController.java with respect to the context of the activity or broadcaster.
AppController.getInstance(this).addToRequestQueue(strReq, tag_string_req);

Awkward session error with magento cookie parsing in Android App

I am working on an Android app which uses sessions by managing cookies from an API based on magento backend.
On the app side, I am using Volley Library for network request. I have successfully got the network response and from that I have fetched the "Set-Cookie" value. Now when I am attaching this cookie to the header but the server doesn't validate my session.
The strange thing is I tried to request the same JSON request from a rest client and then used the cookie from that and added to the header as a static value and then I was provided session access. I completely have no idea regarding what is going on. Why the cookies from rest client is working while the cookie value from my network response doesn't.
Here is my SignIn Activity code where I am doing a login json request and storing the cookie value.
package com.paaltao.activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.ProgressWheel;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import static com.paaltao.extras.Keys.UserCredentials.*;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.LOGIN;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
public class SignInActivity extends AppCompatActivity {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
Button SignUpBtn;
Button SignInBtn;
ProgressWheel progressBar;
EditText email, password;
TextView forgotPassword;
String emailId,accessToken,api_ver,token,firstName,lastName,cookie,newCookie;
Boolean login_success;
SharedPreferenceClass preferenceClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
Toolbar toolbar = (Toolbar) this.findViewById(R.id.app_bar);
toolbar.setTitleTextColor(Color.WHITE);
toolbar.setBackgroundColor(getResources().getColor(R.color.transparent));
this.setSupportActionBar(toolbar);
this.setTitle("Sign in");
initiate();
onItemClick();
}
public void initiate() {
SignUpBtn = (Button) findViewById(R.id.signUpBtn);
email = (EditText) findViewById(R.id.email_field);
password = (EditText) findViewById(R.id.password_field);
SignInBtn = (Button) findViewById(R.id.signInBtn);
forgotPassword = (TextView) findViewById(R.id.forgot_password);
progressBar = (ProgressWheel)findViewById(R.id.action_progress);
preferenceClass = new SharedPreferenceClass(getApplicationContext());
}
public boolean validationCheck() {
if (email.getText().toString().length() == 0)
email.setError("Please provide your email. Your email must be in the format abc#xyz.com");
else if (password.getText().toString().length() == 0)
password.setError("Please provide a password");
else return true;
return false;
}
public void onItemClick() {
SignInBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validationCheck()) {
sendJsonRequest();
}
}
});
SignUpBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SignInActivity.this, ForgotPasswordActivity.class);
startActivity(intent);
}
});
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ LOGIN;
}
public void sendJsonRequest() {
progressBar.setVisibility(View.VISIBLE);
final JSONObject jsonObject = new JSONObject();
final JSONObject signIn = new JSONObject();
try {
jsonObject.put("email", email.getText().toString());
jsonObject.put("password", password.getText().toString());
signIn.put("emailSignIn", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getRequestUrl(), signIn, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
parseJSONResponse(jsonObject);
//Calling the Snackbar
Log.e("response", jsonObject.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (progressBar.getVisibility() == View.VISIBLE) {
progressBar.setVisibility(View.GONE);
}
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(SignInActivity.this)
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
}) {
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
L.m(response.headers.toString());
L.m(Arrays.toString(response.data));
L.m(response.headers.get("Set-Cookie"));
preferenceClass.saveCookiee(response.headers.get("Set-Cookie"));
cookie = response.headers.get("Set-Cookie");
String[] splitCookie = cookie.split(";");
String[] splitSessionId = splitCookie[0].split("=");
newCookie = splitSessionId[1];
//cookie = response.headers.values().toString();
Log.e("split",newCookie);
preferenceClass.saveCookie(newCookie);
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders ()throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
// MyApp.get().addSessionCookie(headers);
return headers;
}
}
;
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signInObject = dataObject.getJSONObject(KEY_SIGN_IN);
JSONObject accessTokenObject = signInObject.getJSONObject(KEY_ACCESS_TOKEN);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
if(dataObject.has(KEY_VENDOR)){
if (dataObject.isNull(KEY_VENDOR)){
return;
}
else {JSONObject vendorObject = dataObject.getJSONObject(KEY_VENDOR);
if(vendorObject != null){
String vendor_login = vendorObject.getString(KEY_HAS_SHOP);
if(vendor_login != null && vendor_login.contains("true")){
preferenceClass.saveVendorLoginSuccess(vendor_login);
}}}
}
emailId = signInObject.getString(KEY_EMAIL);
firstName = signInObject.getString(KEY_FIRST_NAME);
lastName = signInObject.getString(KEY_LAST_NAME);
login_success = signInObject.getBoolean(KEY_USER_LOGIN_SUCCESS);
preferenceClass.saveFirstName(firstName);
preferenceClass.saveLastName(lastName);
preferenceClass.saveUserEmail(emailId);
if(accessTokenObject.has(KEY_TOKEN)){
token = accessTokenObject.getString(KEY_TOKEN);}
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (login_success){
Log.e("TAG",login_success.toString());
if (token!= null && token.length()!=0){
preferenceClass.saveAccessToken(token);
preferenceClass.saveUserEmail(emailId);
Intent intent = new Intent(SignInActivity.this,HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
else{
Log.e("TAG",login_success.toString());
new SnackBar.Builder(SignInActivity.this)
.withMessage("Username or Password is Incorrect!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
and this is the code for the fragment where I am doing a check session test with the stored cookie received from network response (Note: I replaced the cookie with the one I got from rest client and it worked!!)
package com.paaltao.fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpClientStack;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.HttpStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.github.mrengineer13.snackbar.SnackBar;
import com.paaltao.R;
import com.paaltao.activity.AddressActivity;
import com.paaltao.activity.IntroPageActivity;
import com.paaltao.activity.PaaltaoInfo;
import com.paaltao.activity.EditProfileActivity;
import com.paaltao.classes.MyApp;
import com.paaltao.classes.PersistentCookieStore;
import com.paaltao.classes.SharedPreferenceClass;
import com.paaltao.logging.L;
import com.paaltao.network.VolleySingleton;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import cn.pedant.SweetAlert.SweetAlertDialog;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ACCESS_TOKEN;
import static com.paaltao.extras.Keys.UserCredentials.KEY_DATA;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_CODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_ERROR_NODE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_MESSAGE;
import static com.paaltao.extras.Keys.UserCredentials.KEY_SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.BASE_URL;
import static com.paaltao.extras.urlEndPoints.SIGN_OUT;
import static com.paaltao.extras.urlEndPoints.UAT_BASE_URL;
//This is a user account fragment.
public class AccountFragment extends Fragment {
private static final String SET_COOKIE_KEY = "Set-Cookie";
private static final String COOKIE_KEY = "Cookie";
private static final String SESSION_COOKIE = "sessionid";
RelativeLayout accountLink,my_address,signOut;
View view;
String accessToken;
TextView firstName,lastName,about,terms,privacy,notificationSettings;
SharedPreferenceClass preferenceClass;
SweetAlertDialog dialog;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_account, container, false);
initialize();
onItemClick();
return view;
}
public static String getRequestUrl() {
return UAT_BASE_URL
+ SIGN_OUT;
}
public void sendJsonRequest(){
final JSONObject jsonObject = new JSONObject();
final JSONObject signOut = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
signOut.put("signOut", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl(),signOut,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", signOut.toString());
parseJSONResponse(jsonObject);
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
new SnackBar.Builder(getActivity())
.withMessage("No Internet Connection!")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
});
requestQueue.add(jsonObjectRequest);
}
public void parseJSONResponse(JSONObject jsonObject) {
if (jsonObject == null || jsonObject.length() == 0) {
return;
}
try {
JSONObject dataObject = jsonObject.getJSONObject(KEY_DATA);
JSONObject signOutObject = jsonObject.getJSONObject(KEY_SIGN_OUT);
JSONObject errorNodeObject = dataObject.getJSONObject(KEY_ERROR_NODE);
accessToken = signOutObject.getString(KEY_ACCESS_TOKEN);
String errorCode = errorNodeObject.getString(KEY_ERROR_CODE);
String message = errorNodeObject.getString(KEY_MESSAGE);
if (errorCode.equals("200")){
preferenceClass.clearAccessToken();
preferenceClass.clearFirstName();
preferenceClass.clearLastName();
preferenceClass.clearUserEmail();
Log.e("accessToken",accessToken);
Intent intent = new Intent(getActivity(),IntroPageActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
}
else{
new SnackBar.Builder(getActivity())
.withMessage("Error in signing out")
.withTextColorId(R.color.white)
.withDuration((short) 6000)
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void sendJsonRequest1(){
final JSONObject jsonObject = new JSONObject();
final JSONObject sessionCheck = new JSONObject();
try{
jsonObject.put("accessToken","67drd56g");
sessionCheck.put("checkSession", jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
RequestQueue requestQueue = VolleySingleton.getsInstance().getRequestQueue();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,getRequestUrl1(),sessionCheck,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
Log.e("error", jsonObject.toString());
Log.e("json", sessionCheck.toString());
Log.e("url",getRequestUrl());
L.m(jsonObject.toString());
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
if (volleyError instanceof TimeoutError || volleyError instanceof NoConnectionError) {
} else if (volleyError instanceof AuthFailureError) {
//TODO
} else if (volleyError instanceof ServerError) {
//TODO
} else if (volleyError instanceof NetworkError) {
//TODO
} else if (volleyError instanceof ParseError) {
//TODO
}
}
})
{
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
// since we don't know which of the two underlying network vehicles
// will Volley use, we have to handle and store session cookies manually
// MyApp.get().checkSessionCookie(response.headers);
//L.m(response.headers.toString());
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = super.getHeaders();
if (headers == null
|| headers.equals(Collections.emptyMap())) {
headers = new HashMap<String, String>();
}
String sessionId = preferenceClass.getCookie();
Log.e("cOOOKIE","frontend="+sessionId);
Log.e("sessionid","frontend=7fgenogpffjvvmdg1gf439hta7");
// headers.put(COOKIE_KEY,"frontend="+sessionId);
headers.put(COOKIE_KEY,"frontend=e7qfldgsnf7aop381a8vk3b866");
return headers;
}};
requestQueue.add(jsonObjectRequest);
}
private String getRequestUrl1() {
return UAT_BASE_URL+"checkSession";
}
public void initialize(){
accountLink = (RelativeLayout)view.findViewById(R.id.account_link);
my_address = (RelativeLayout)view.findViewById(R.id.my_address);
signOut = (RelativeLayout)view.findViewById(R.id.signOut);
preferenceClass = new SharedPreferenceClass(getActivity());
firstName = (TextView)view.findViewById(R.id.firstName);
lastName = (TextView)view.findViewById(R.id.lastName);
about = (TextView)view.findViewById(R.id.about);
terms = (TextView)view.findViewById(R.id.terms);
privacy = (TextView)view.findViewById(R.id.privacy);
if(preferenceClass.getFirstName() != null)
firstName.setText(preferenceClass.getFirstName());
if(preferenceClass.getLastName() != null)
lastName.setText(preferenceClass.getLastName());
notificationSettings = (TextView)view.findViewById(R.id.notification_settings);
}
public void onItemClick(){
notificationSettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendJsonRequest1();
}
});
accountLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), EditProfileActivity.class));
}
});
my_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), AddressActivity.class));
}
});
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
confirmSignOut();
}
});
about.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","about_paaltao");
startActivity(intent);
}
});
terms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","terms");
startActivity(intent);
}
});
privacy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PaaltaoInfo.class);
intent.putExtra("page","privacy_policy");
startActivity(intent);
}
});
}
public void confirmSignOut(){
dialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.NORMAL_TYPE);
dialog.setTitleText("Signout")
.setContentText("Are you sure you want to sign out?")
.setConfirmText("Yes")
.setCancelText("No")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sendJsonRequest();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
dialog.cancel();
}
})
.show();
}
}
There is no structural difference between the rest client cookie and the one recieved in app:
rest client cookie : frontend=48b1i38fgls4d0241mp6d6rrr0
app side cookie : frontend=86n349m3patu37eud00ntobd90
Thanks in advance. It will be a life saver if some one can help.

Using volley library inside a library

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.

Categories

Resources