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.
in my Android project i try to prepare waiting mechanism or correct synchronize to intent service to handle multi concurrency requests user. for example after click on button, my application try to get data on server with Service,
after click on the button, user maybe try to click on that again, for manage this operation i coding below sample to handle multi concurrency requests user, such as waiting to finish request with create an requests path.
but in this code i cont know how to create requests stack, that means they must run by order's requests.
now is my code correct?
Volley Simple Singleton Class:
public class CustomVolleyRequestQueue {
private static CustomVolleyRequestQueue mInstance;
private static Context context;
private RequestQueue mRequestQueue;
private CustomVolleyRequestQueue(Context context) {
this.context = context;
mRequestQueue = getRequestQueue();
}
public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleyRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
// start the volley request queue
mRequestQueue.start();
}
return mRequestQueue;
}
}
Intent Service:
public class WebService extends IntentService {
public static final String REQUEST_TAG = "SimpleWebServiceBlockingRequest";
private RequestQueue mQueue;
private Object isReceiveMessagesLock;
public WebService() {
super("WebService");
}
public WebService(String name) {
super("WebService");
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Bundle data = intent.getExtras();
if (data != null) {
String url = data.getString("url");
synchronized (isReceiveMessagesLock) {
if (isReceiveMessagesLock != null) {
return;
} else {
try {
isReceiveMessagesLock.wait();
startParsingTask(url); //receiving start
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public void startParsingTask(final String url) {
Thread prepaire_request_thread = new Thread() {
public void run() {
ThreadB request_from_servcer_thread = new ThreadB(getApplicationContext(), url);
JSONObject json_object = null;
try {
json_object = request_from_servcer_thread.execute().get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
if (json_object != null) {
Log.e("OUTPUT: ", json_object.toString());
}
}
};
prepaire_request_thread.start();
}
private class ThreadB extends AsyncTask<Void, Void, JSONObject> {
private Context context;
private String fetch_url = "";
public ThreadB(Context ctx, String url) {
context = ctx;
this.fetch_url = url;
}
#Override
protected JSONObject doInBackground(Void... params) {
final RequestFuture<JSONObject> futureRequest = RequestFuture.newFuture();
mQueue = CustomVolleyRequestQueue.getInstance(context.getApplicationContext())
.getRequestQueue();
final JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method
.GET, fetch_url,
new JSONObject(), futureRequest, futureRequest);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
try {
return futureRequest.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
return null;
}
}
}
POST UPDATED:
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Bundle data = intent.getExtras();
if (data != null) {
String url = data.getString("url");
startParsingTask(url); //receiving start
}
}
}
IntentService already handles one call per time, you don't need syncronize or anything else.
Volley supports also multiple calls, so you won't have any problem of concurrency at all.
After that, if you are calling APIs, you may want to try retrofit ( http://square.github.io/retrofit/ ) or at least use GSON to deserialize JSON data.
*how to create interface use any where android Json Volley Library please help me *
public void getJsonRequest(){//Create interface and jsonObjectRequest
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
list =parseJSONRequest(response);// create interface
adapter.setAllLinks(list); // create interface
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
errorJson.setVisibility(View.VISIBLE);
String map = VolleyErrorException.getErrror(error, getContext());
errorJson.setText(map);
}
});
requestQueue.add(jsonObjectRequest);
}
Here is solution. I have created a static method in a separate class nammed APIManager.
/**
* The method to create a Request with specific method except GET
*
* #param method The request Method ex. (Request.Method.POST)
* #param params The parameters map
* #param url The base url of webservice to be called
* #param requestTag The request Tag to assign when putting request to request queue
* #param listener The listener for request completion.
*/
public static void createPostRequest(int method, final Map<String, String> params, String url, String requestTag, final OnRequestCompletedListener listener) {
JsonObjectRequest request = new JsonObjectRequest(method, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
listener.onRequestCompleted(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
listener.onRequestError(getErrorMessageFromVolleyError(error));
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
#Override
public byte[] getBody() {
Uri.Builder builder = Uri.parse("http://example.com")
.buildUpon();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(),
entry.getValue());
}
return builder.build().getEncodedQuery().getBytes();
}
};
AppController.getInstance().addToRequestQueue(request, requestTag);
}
/**
* The interface for callback when API Request completes.
*/
public interface OnRequestCompletedListener {
/**
* The interface method called when API call successfully completes.
*
* #param jsonObject The JSONObject recieved from the API call.
*/
void onRequestCompleted(JSONObject jsonObject);
/**
* The interface method called when API call recieves any Error.
*
* #param errorMessage The error message
*/
void onRequestError(String errorMessage);
}
/**
* The method to convert volley error into user readable string message.
*
* #param error The volleyError recieved during API call
* #return The String containing the message related to error
*/
public static String getErrorMessageFromVolleyError(VolleyError error) {
if (error instanceof TimeoutError) {
return AppController.getContext().getString(R.string.time_out_error_message);
}
if (error instanceof NoConnectionError) {
return AppController.getContext().getString(R.string.no_connection_error_message);
}
if (error instanceof ServerError) {
return AppController.getContext().getString(R.string.server_error_message);
}
if (error instanceof NetworkError) {
return AppController.getContext().getString(R.string.network_error_message);
}
if (error instanceof ParseError) {
return AppController.getContext().getString(R.string.parse_error_message);
}
return null;
}
To call this method use it in any activity or fragment class like this way.
private void getEvaultFiles() {
Map<String, String> params = new HashMap<>();
params.put("EvaultId", item.id);
APIManager.createPostRequest(Request.Method.POST,params, AppConstants.GET_EVAULT_FILES_URL, "GETEVAULTFILES", new APIManager.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(JSONObject jsonObject) {
Utils.hideProgressAndShowContent(EvaultDetailActivity.this);
listFiles.clear();
tvEmpty.setText("No Files to display");
try {
JSONArray files = jsonObject.getJSONObject("Result").getJSONArray("Files");
for (int i = 0; i < files.length(); i++) {
EvaultFile file = new EvaultFile();
JSONObject temp = files.getJSONObject(i);
file.name = temp.getString("FileName");
file.size = temp.getString("FileSize");
file.fileurl = temp.getString("FilePathFullImage");
listFiles.add(file);
}
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onRequestError(String errorMessage, JSONObject data) {
}
});
}
I have a project: myApp
these files...
- myFragment.java.
- myDialogFragment.java.
- myAsyncTask.java
I have a project: myLibrary
This project "is Library" of "myApp"
I have...
- myMethodsToUpload.java
One of these methods, have a While bucle for write the file on php server.
Everything works like magic! :)
and the reason for the file structure is to make the library reusable.
but...
How can I send the increments of a value inside of this While bucle, to myAsyncTask.java?
Considering that...
what I want to do... is to make "myMethodsToUpload.java", reusable.
Some code...
myFragment.java
myDialogFragment df = new myDialogFragment();
df.setMyThings(new myAsynctask(), myParameters);
df.setTargetFragment(this, 0);
df.show(getFragmentManager(), DIALOG_FRAGMENT_TAG);
.
myDialogFragment.java
public class myDialogFragment extends DialogFragment {
myAsyncTask async;
public void setMyThings(myAsynctask inAsynctask, String[] inArray){
async = inAsynctask;
async.sendFragment(this);
parameters = inArray;
}
//...
//Only called from "myAsyncTask.java"
public void updateFromAsyncTask(Integer porcent){
progressbar.setProgress(porcent);
}
//...
}
.
myAsyncTask.java
public class myAsynctask extends AsyncTask<String, Integer, String> {
void sendFragment(myDialogFrament inFragment){
myDialogFrament = inFragment;
}
//...
#Override
protected String doInBackground(String... inArray) {
String urlPHP = inArray[0];
String pathImg = inArray[1];
String paramValue = inArray[2];
String msj = "";
try {
methodsToUpload up = new methodsToUpload(urlPHP);
up.connectNow();
up.insertFile(pathImg);
up.insertParams("pName", paramValue);
up.insertFinish();
msj = up.coonectClose();
} catch (Exception e) {
e.printStackTrace();
}
return msj;
}
//Called from "myMethods.java"
public void updateFromAsyncTask(int porcent){
publishProgress(porcent);
}
#Override
protected void onProgressUpdate(Integer... inPorcent) {
if(myDialogFragment == null){
return;
}
myDialogFragment.updateFromAsyncTask(inPorcent[0]);
}
}
.
myMethodsToUpload.java
public class myMethodsToUpload {
//...
public myMethodsToUpload(String url_in){
this.url = url_in;
}
public void insertFile(String path) throws Exception {
//...
//...
while (bytesRead > 0) {
salidaStream.write(buffer, 0, bufferSize);
sendedPorcent += bytesRead;
completedPorcent = (int) (sendedPorcent * 100 / fileSize);
//This line doesn't work...
//because myAsyncTask.java, is in another project.
myAsyncTask.updateFromAsyncTask(completedPorcent);
bytesAvailable = archivoStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = archivoStream.read(buffer, 0, bufferSize);
}
//...
//...
}
}
.
I've already tried...
"MyLibrary" -> propeties -> java build path -> projects -> add -> Project(myApp)
but...
throws me errors:
W/System.err(32469): at java.util.concurrent.FutureTask.run(FutureTask.java:237)...
ThreadPoolExecutor.runworker...
etc.
And, in the status bar of eclipse appears every moment "Building Workspace (X%)"
I'm a newbie, but I think the error happens because "MyLibrary" is Library of "MyApp", and I'm trying use "java build path".
So... how can I resolve this?, I'm lost!!!
sorry by my english... thanks in advance! :)
Here is a simple exemple :
Your AsyncTask class :
private CallBack mCallback;
public static interface CallBack {
public void updateValue(int value);
}
public void setCallBack(CallBack callBack){
this.mCallBack = callBack;
}
#Override
protected void onProgressUpdate(Integer... inPorcent) {
mCallback.updateValue(inPorcent[0].intValue());
}
Your fragment class :
public class Fragment extends Fragment implements Callback {
private AsyncTask yourAsyncTask;
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yourAsyncTask = new AsyncTask();
yourAsyncTask.setCallBack(this);
yourAsyncTask.excecute();
}
#Override
public void updateValue(int value){
Log.e(TAG,"Value : " + value);
}
}
EDIT 1 :
public class AdsHttpRequest {
private static final String TAG = AdsHttpRequest.class.getSimpleName(); // log
private GetHttpTask mGetAsyncTask;
private static AdsHttpRequest mInstance;
private OnGetRequestListener mCallBack;
private static final String SUCCESS = "success";
private static final String SUCCES = "succes";
private static final String FAILED = "fail";
/**
* #return a singleton instance of {#link AdsHttpRequest}
*/
public static AdsHttpRequest getInstance() {
if (mInstance == null) {
synchronized (AdsHttpRequest.class) {
if (mInstance == null) {
mInstance = new AdsHttpRequest();
}
}
}
return mInstance;
}
/**
* Initialize the {#link AsyncTask}, set the callback, execute the task
*
* #param url
* url for the request
* #param callback
* {#link OnGetRequestListener} for feed back
*/
public void post(String url, OnGetRequestListener callback) {
mCallBack = callback;
if (mGetAsyncTask == null) {
mGetAsyncTask = new GetHttpTask();
} else {
cancelGetTask();
mGetAsyncTask = new GetHttpTask();
}
mGetAsyncTask.execute(url);
}
/**
* cancel the {#link AsyncTask} if it's still alive <br>
* <b>see </b> {#link Status}
*/
public void cancelGetTask() {
if (mGetAsyncTask != null && mGetAsyncTask.getStatus().equals(Status.RUNNING)) {
mGetAsyncTask.cancel(true);
}
mGetAsyncTask = null;
}
private AdsHttpRequest() {
super();
}
/**
* Actually construct and launch the HTTP request
*
* #param url
* url of the request
* #return response of the server
*/
private String getResponseFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (Exception e) {
Log.e(TAG, "", e);
}
return xml;
}
/**
* Manage the http request in background
*
* #param String
* url for the request
*/
private class GetHttpTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0] != null) {
return getResponseFromUrl(params[0]); // return the response of the server
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
if (result.contains(SUCCES) || result.contains(SUCCESS)) {
mCallBack.onGetRequestResult(SUCCESS);
} else {
mCallBack.onGetRequestResult(FAILED);
}
}
}
}
}
The way that I'm doing this consume more memory, time, threads? (I'm guessing)
I'm have add volley for request to get Json object and cache data. but when i clear all cache, seem all data not delele.
Because when i turn off my network and restart my app .It still using cache.
I do the following code
public class AppController extends Application {
public static final String TAG = AppController.class.getName();
public static AppController mIntance;
private RequestQueue requestQueue;
private ImageLoader imageLoader;
/**
* onCreate of class that is extend Application always call first when app laucher . to benefit
* create object singleton.
*
* #param err
* #param context
* #return
*/
#Override
public void onCreate() {
super.onCreate();
mIntance = this;
}
public static synchronized AppController getIntance() {
return mIntance;
}
public RequestQueue getRequestQueue() {
/*
* if (requestQueue == null) { requestQueue =
* MyRequest.newRequestQueue(getApplicationContext()); }
*/
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// hoa ra settag la cho req nay ,. minh cu tuong no set cho c�i
// requestqueue
req.setTag(tag.equals("") ? TAG : tag);
getRequestQueue().add(req);
}
// using request with string default
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelRequest(Object tag) {
if (requestQueue != null) {
requestQueue.cancelAll(tag);
}
}
public void cancelAllRequest() {
if (requestQueue != null) {
requestQueue.cancelAll("feed_request");
}
}
/*
* clear some cache
*/
public void DeletelCacheFromSomeURL(ArrayList<String> array) {
for (int i = 0; i < array.size(); i++) {
requestQueue.getCache().remove(array.get(i));
}
}
}
i have clear all cache flowing
AppController.getIntance().getRequestQueue().getCache()
.clear();
Anyone explain and give me solution . thank !