Android App , how to communicate between Activity, Service and SyncAdapter - android

Hi Im working on an android app which works both online and offline. So if its connected to wifi , when i click on save button in the Activity , there are multiple requests (StringRequest) sent to server to update the db. And if offline it saves the data to sqlite and once wifi is available, it automatically syncs the data using SyncAdapter. My problem is there is lot of redundant/duplicate code - one for Activity and one for SyncAdapter and i'm trying to cleanup the code. The only difference between the both for each StringRequests in Activity , Response.Listener & Response.ErrorListener shows some alerts in the Activity and in SyncAdapter it just logs the messages.
Now i have written a Service class that can be used by both activity and syncadapter , the question i have is how can i send alerts/updates to activity in the Response.Listener & Response.ErrorListener , without breaking the flow of service methods.
private void Method1 () {
if (NetworkConnection.isNetworkAvailable (this))
{
StringRequest strRequest = new StringRequest (Request.Method.POST, AppConfigURL.API_URL,
new Response.Listener<String> () {
#Override
public void onResponse (String response) {
if (response != null) {
Utils.showLog (Log.INFO, AppConfigTags.SERVER_RESPONSE, response, true);
} else {
Utils.showOkDialog (MainActivity.this, "Custom alert message", false);
}
Method2();
}
},
new Response.ErrorListener () {
#Override
public void onErrorResponse (VolleyError error) {
Utils.showLog (Log.ERROR, AppConfigTags.VOLLEY_ERROR, error.toString (), true);
Method2();
}
}) {
#Override
public byte[] getBody () throws com.android.volley.AuthFailureError {
JSONObject sendJSON = db.getOfflineSavedOrderDetails();
String str = "{\"API_username\":\"" + Constants.api_username + "\",\n" +
"\"API_password\":\"" + Constants.api_password + "\",\n" +
"\"API_function\":\"updateSavedFixedDetails\",\n" +
"\"API_parameters\": " + String.valueOf(sendJSON) + "}";
Utils.showLog (Log.INFO, AppConfigTags.PARAMETERS_SENT_TO_THE_SERVER, str, true);
return str.getBytes ();
}
public String getBodyContentType () {
return "application/json; charset=utf-8";
}
};
AppController.getInstance().addToRequestQueue(strRequest);
} else {
Method2();
}
}
private void Method2 () {
if (NetworkConnection.isNetworkAvailable (this))
{
StringRequest strRequest = new StringRequest (Request.Method.POST, AppConfigURL.API_URL,
new Response.Listener<String> () {
#Override
public void onResponse (String response) {
if (response != null) {
Utils.showLog (Log.INFO, AppConfigTags.SERVER_RESPONSE, response, true);
} else {
Utils.showLog (Log.WARN, AppConfigTags.SERVER_RESPONSE, AppConfigTags.DIDNT_RECEIVE_ANY_DATA_FROM_SERVER, true);
}
Method3();
}
},
new Response.ErrorListener () {
#Override
public void onErrorResponse (VolleyError error) {
Utils.showOkDialog (MainActivity.this, "Connection Error: My custom error", false);
Method3();
}
}) {
#Override
public byte[] getBody () throws com.android.volley.AuthFailureError {
JSONObject sendJSON = db.getOfflineSavedOrderDetails();
String str = "{\"API_username\":\"" + Constants.api_username + "\",\n" +
"\"API_password\":\"" + Constants.api_password + "\",\n" +
"\"API_function\":\"updateContractDetails\",\n" +
"\"API_parameters\": " + String.valueOf(sendJSON) + "}";
Utils.showLog (Log.INFO, AppConfigTags.PARAMETERS_SENT_TO_THE_SERVER, str, true);
return str.getBytes ();
}
public String getBodyContentType () {
return "application/json; charset=utf-8";
}
};
AppController.getInstance().addToRequestQueue(strRequest);
} else {
Method3();
}
}

Related

how to fetch limited data using api in retrofit

Im able to fetch data using retrofit in android and able to set it view in recyclerView using adapter.but the thing is i don't want to fetch whole data from my api i want to remove some data from my api using java which should not be visible in recyclerview.
Android studio, java
private void getSearchProduct(String str_search_text, String page_no, String limit, final String catid) {
final ProgressDialog progressDialog = new ProgressDialog (this);
if (limit.equalsIgnoreCase ("")) {
progressDialog.show ();
progressDialog.setMessage ("Please wait...");
progressDialog.setCancelable (false);
} else {
progressDialog.setMessage ("Please wait...");
progressDialog.setCancelable (false);
}
if (page_no.equalsIgnoreCase ("")) {
pagenonew = "";
} else {
pagenonew = page_no;
}
Log.e (TAG, "getSearchProduct: catid..............." + catid);
if (catid.equals ("")) {
category_id = catid;
Log.e (TAG, "getSearchProduct: catid" + catid);
}
apiService = ApiUtils.getAPIService ();
apiService.getSearchProduct ("" + latitude, "" + longitude, CustomerID, str_search_text, pagenonew, catid).enqueue (new Callback<Search_Product_Model> () {
#Override
public void onResponse(Call<Search_Product_Model> call, Response<Search_Product_Model> response) {
if (response.isSuccessful ()) {
int status = response.body ().getStatus ();
String meg = response.body ().getMsg ();
if (status == 1) {
serach_product_lists.clear ();
serach_product_lists = response.body ().getProductList ();
/* categoryID = response.body ().getCategory_id ();
Log.e (TAG, "categoryID: categoryID......" + categoryID);*/
Search_Product_Adapter adapter = new Search_Product_Adapter (SearchProduct_Fragment.this, serach_product_lists);
recycler_views_category_offerzone.setAdapter (adapter);
txt_noproduct.setVisibility (View.GONE);
recycler_views_category_offerzone.setVisibility (View.VISIBLE);
} else {
txt_noproduct.setVisibility (View.VISIBLE);
txt_noproduct.setText (meg);
recycler_views_category_offerzone.setVisibility (View.GONE);
}
progressDialog.dismiss ();
} else {
progressDialog.dismiss ();
}
}
#Override
public void onFailure(Call<Search_Product_Model> call, Throwable t){
progressDialog.dismiss ();
}
});
}
I think you should use RxJava in combination with Retrofit (they really work amazingly togheter) that has operator take which allows you to choose how many result to take
Observable.just(1, 2, 3, 4, 5, 6, 7, 8)
.take(4)
.subscribe(new Subscriber<Integer>() {
#Override
public void onNext(Integer item) {
System.out.println("Next: " + item);
}
#Override
public void onError(Throwable error) {
System.err.println("Error: " + error.getMessage());
}
#Override
public void onCompleted() {
System.out.println("Sequence complete.");
}
});
for more documentation please look at http://reactivex.io/documentation/operators/take.html
for combining Retrofit and RxJAva
https://www.journaldev.com/20433/android-rxjava-retrofit
Ask your service provider don't return the data you don't want to fetch.
Traverse your data list to find the data you don't want then remove them .As the following codes!
serach_product_lists = response.body ().getProductList ();
for(data:serach_product_lists){
if(//put your judge code here)
serach_product_lists.remove(data)
}

How to pass RAW body to the API using volley android

I am trying to POST body with my api of XML type. Please have a look at the body below! I have no clue how to pass xml body with the api
<passwordQuestions>
 <passwordQuestion question="security.question.childhood.nickname" answer="nickname"/>
   <passwordQuestion question="security.question.father.middleName" answer="father.middleName"/>
   <passwordQuestion question="security.question.oldestSibling.middleName" answer="oldestSibling.middleName"/>
</passwordQuestions>
type:
Content-Type text/xml
This is my code need to add body here!
public void setSeqQns(String oldAPIEmail, String token,String appKey, String mLocale, String firstQuestion, String firstAnswer,
String secondQuestion, String secondAnswer, String thirdQuestion, String thirdAnswer,
final Action1<String> onUpdateSetAnswerSuccess, final Action1<String> onUpdateSetAnswerFail) {
if(userId == null){
Log.e(TAG, "userId is null");
Observable<String> observable = Observable.just("userId is null");
observable.subscribe(onUpdateSetAnswerFail);
return;
}
String url = BASE_URL + Util.addUseridToUri(URI_SET_ANSWER, userId);
Response.Listener<String> listener =
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.v(TAG, "Update seq qns response: "+ response);
Observable<String> observable = Observable.just(response);
observable.subscribe(onUpdateSetAnswerSuccess);
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
String errorCode = null;
if (error.networkResponse != null) {
Map<String, String> headers = error.networkResponse.headers;
if (headers != null) {
errorCode = headers.get(PulseAPIConstants.HEADER_XIcErrorCode);
Log.e(TAG, "received error code: " + errorCode);
}
}
// observes this API request and will call the loginFailure action
Observable<String> observable = Observable.just(errorCode);
observable.subscribe(onUpdateSetAnswerFail);
}
};
AuthenticatedGsonRequest<String> request = new AuthenticatedGsonRequest<>(
Request.Method.POST,
url,
new TypeToken<String>() {}.getType(),
null,
listener,
errorListener,
oldAPIEmail,
token,
appKey,
mLocale);
addToRequestQueue(request, TAG_SET_ANSWER);
}
I need to add xml(RAW body data) to the URI.
Thanks!!

Android Volley Request Identity onErrorResponse Section

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

android How to asynchronous request data and synchronous display data

I have two listview in my activity. I use asynhttpclient request data two times, but I don't know how to monitor the two times request to refresh my listview.
There are some codes.
loadData( Constant.newGameUrl ,"new");
loadData( Constant.hotGameUrl ,"hot");
/**
* request data
* #param url
* #param type
*/
public void loadData( String url,
final String type,final int initpage){
H5RestClient.request(url, null, new OnRequestListener(){
#SuppressLint("ShowToast")
#Override
public void onRequestFinish(boolean ret, String data) {
// TODO Auto-generated method stub
List<Game> games = new ArrayList<Game>();
if( ret == true ){
try {
games = JsonParseUtil.parseGame(data);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if( games != null ){
netStateView.show(NetState.CONTENT);
if( type.equals("new")){
listNew.addAll(games);
newAdapter.notifyDataSetChanged();//this listview
}else if( type.equals("hot") ){
listHot.addAll(games);
hotAdapter.notifyDataSetChanged();//I want to display the two list view
}
}
else{
Toast.makeText(context, "result is null", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(context, "request is failed", Toast.LENGTH_SHORT).show();
}
}
});
}
public static void request(final String url, final RequestParams params, final OnRequestListener listener) {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, String responseBody){
Log.i(TAG, "success "+responseBody);
listener.onRequestFinish(true, responseBody);
}
#Override
public void onFailure(Throwable e, String responseBody){
Log.e(TAG, "fail "+responseBody);
listener.onRequestFinish(false, responseBody + "");
}
};
client.get(url, handler);
}
How to display the two listview at the same time?
newAdapter.notifyDataSetChanged();//this listview
hotAdapter.notifyDataSetChanged();//I want to display the two list view
I recommend you to use Google Volley librairy for HTTP request.
See the doc here : http://developer.android.com/training/volley/index.html
Some code for your problem :
StringRequest strRequest1 = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// CODE REQUEST 1
}
}, 0, 0, null, null);
StringRequest strRequest2 = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// CODE REQUEST 2
}
}, 0, 0, null, null);
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(strRequest1);
rq.add(strRequest2);
Two booleans, one per transaction. Once a transaction is complete, it checks the two boolean. If the two are true, you display your data, if not it only sets its boolean to true...

loopj AsyncHttpClient more then 3 post not working

I am starting then 4 post after each other. But I catch only response from 3 of the 4 posts.
Can somebody explain to me why? I tried it also with get and it has the same problem. Am I doing the posts to quick after each other?
Resclient class:
public class RestClient {
private static AsyncHttpClient client = new AsyncHttpClient();
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
}
Webservice resolver:
public class WSBeer extends WSBase {
public WSBeer(OnWSRequestCompleted listener, Context context) {
super(listener, context);
}
public void getAll(String date) throws JSONException {
Tools.LOG_DEBUG("GetAllBeer");
RequestParams params = new RequestParams();
params.add("date", date);
RestClient.post(url, params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(JSONObject response) {
Tools.LOG_DEBUG("WSBeer onSucces: " + response);
listener.onRestTaskCompleted(Constants.FUNCTION_DB_BEER, response);
}
#Override
public void onFailure(Throwable e, JSONArray errorResponse) {
Tools.LOG_DEBUG("WSBeer getAll: " + errorResponse);
handleError(e, errorResponse, null);
}
#Override
public void onFailure(Throwable e, JSONObject errorResponse) {
Tools.LOG_DEBUG("WSBeer getAll: " + errorResponse);
handleError(e, null, errorResponse);
}
});
}
}
SyncHandler class:
public class SyncHandler implements OnWSRequestCompleted {
private OnSyncListener listener;
private Context context;
private WSBeer wsBeer;
public SyncHandler(OnSyncListener listener, Context context) {
this.listener = listener;
this.context = context;
}
#Override
public void onRestTaskCompleted(int function, JSONObject response) {
switch (function) {
case Constants.FUNCTION_DB_BEER:
List<Beer> beerList = null;
try {
beerList = ResponseBeer.getAll(response);
} catch (IOException e) {
Tools.LOG_ERROR(e);
}
Tools.LOG_DEBUG("Beers");
if (beerList != null) {
new SaveBeerHelper(listener).execute(beerList.toArray(new Beer[beerList.size()]));
}
break;
}
}
public void syncBeer() {
wsBeer = new WSBeer(this, context);
try {
Tools.LOG_DEBUG("Start loading beer...");
String date = getSyncDate(Constants.FUNCTION_DB_BEER);
wsBeer.getAll(date);
} catch (JSONException e) {
e.printStackTrace();
}
}
private String getSyncDate(int databaseId) {
SyncData syncData = Shared.dbRepo.syncRepository.getById(databaseId);
if (syncData != null) {
Tools.LOG_DEBUG("SyncData: " + syncData.getSyncDate().toString());
return syncData.getSyncDate().toString();
} else {
new SyncData(databaseId).Save(Shared.dbRepo);
}
Tools.LOG_DEBUG("SyncData: ");
return "";
}
}
WEBSERVICE ACTION:
public function bierenAction()
{
$this->view->status = 204; //Nog geen content
if ($this->getRequest()->isPost()){
$date = $this->postParam('date');
if ($date != "") {
$bieren = self::$proxyBier->getBierenByUpdated($date);
} else {
$bieren = self::$proxyBier->getBieren();
}
} else {
$bieren = self::$proxyBier->getBieren();
}
$this->view->data = $bieren;
$this->view->status = 200; //Alles oke
$this->view->ajax();
}
Also you can use this instead https://github.com/leonardoxh/AsyncOkHttpClient this library just use OkHttpClient instead of Apache librarys, and this library is the base codes for Loopj AsyncHttpClient 2.0 (where the library will be re implemented with Square OkHttp)
I used the newer version of async-http library
compile 'com.loopj.android:android-async-http:1.4.5-SNAPSHOT'
and everything works like a charm :)

Categories

Resources