AcitivtyName.this.finish() is not working in callbacks - android

I have written a Class to perform network operation using Volley and have callback passed in the method.
Code is as below
public class MyNetUtil {
public interface MyNetCallbacks {
public void onResponse(String response);
public void onErrorResponse(VolleyError error);
public void onErrorResponseData(ErrorResponseData error);
public void onResponseCode(int code);
}
private void request(int method, String url, final Map<String, String> headMap, final byte[] bodyContent, final MyNetCallbacks myNetCallbacks) {
Log.d(TAG, " Getting url : " + url);
final StringRequest strReq = new StringRequest(method, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
if (myNetCallbacks != null) {
myNetCallbacks.onResponse(response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int statusCode = -1;
if (error != null && error.networkResponse != null) {
statusCode = error.networkResponse.statusCode;
}
VolleyLog.d(TAG, "Error: " + error.getMessage());
ErrorResponseData errorResponseData = null;
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
String errorResponse = new String(response.data);
if (statusCode == -1) {
statusCode = response.statusCode;
}
errorResponseData = ErrorResponseData.getResponseData(errorResponse);
}
if (myNetCallbacks != null) {
myNetCallbacks.onErrorResponse(error);
if (statusCode != -1) {
myNetCallbacks.onResponseCode(statusCode);
}
myNetCallbacks.onErrorResponseData(errorResponseData);
}
Log.d(TAG, " inside onErrorResponse " + statusCode);
}
}) {
// protected Map<String, String> getParams() {
// return stringMap;
// }
#Override
public byte[] getBody() throws AuthFailureError {
Log.d(TAG, "Body : " + new String(bodyContent));
return bodyContent;
}
#Override
public String getBodyContentType() {
return CONTENT_TYPE_APPLICATION_JSON;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d(TAG, " inside parseNetworkResponse, responseCode : " + response.statusCode);
if (myNetCallbacks != null) {
myNetCallbacks.onResponseCode(response.statusCode);
}
return super.parseNetworkResponse(response);
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", CONTENT_TYPE_APPLICATION_JSON);
headers.put("Accept", "application/api.ryder.v2");
headers.put("Authentication-Token", getAuthToken());
if (headMap != null) {
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headers.put(entry.getKey() + "", entry.getValue() + "");
}
}
Log.d(TAG, " Header ");
Util.displayMap(TAG, headers);
return headers;
}
};
BaseApplication.getInstance().addToRequestQueue(strReq, "");
}
}
In my Activity I use it as
private MyNetUtil mMyNetUtil = new MyNetUtil();
mMyNetUtil.request(Request.Method.DELETE, url, headMap, bodyContent, new MyNetUtil.MyNetCallbacks() {
#Override
public void onResponse(String response) {
showProgress(false);
}
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
}
#Override
public void onErrorResponseData(ErrorResponseData error) {
showProgress(false);
}
#Override
public void onResponseCode(int code) {
showProgress(false);
setInfoMessage(R.string.alert__lbl__your_account_was_deleted_successfully);
Log.d(TAG, "onResponseCode " + code);
if (code == MyNetUtil.CODE_204) {
Log.d(TAG, "FINISH --------- " + code);
DataUser.deleteUserFromPref();
Toast.makeText(mContext, R.string.alert__lbl__your_account_was_deleted_successfully, Toast.LENGTH_SHORT).show();
ActivityProfile.this.finish();
return;
} else {
setErrorMessage(R.string.server_error);
}
}
});
Control is going till ActivityProfile.this.finish();
but the activity is not getting finished
I tried onBackPressed also that also not working.
But when I call ActivityProfile.this.finish() out side callback it getting finished
what could be the issue, please help me

You should only call finish from the UI thread.

parseNetworkResponse runs on non UI thread.
That was the issue.

Use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
MainActivity.this.finish();
}
});
See also this post.
Or check this.

Related

Out of memory error using Volley using timers

I have this issue with Volley library requests. I make calls to API and since they have to be updated very often I implemented timers. After some time it throws me error:"Throwing OutOfMemoryError “pthread_create (1040KB stack) failed: Try again. I used the method which was suggested in this post: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again" when doing asynchronous posts using Volley , but for me it did not work, the data coming from API stopped updating. I thought it might be something with timers or it is just something I am doing wrong using Volley.
If you have any idea, feel welcome to share.
My printer class
public void setMenuInformation(String url, Context context, final VolleyCallback callback) {
Log.d("API", "Currently calling URL " + url);
if (eRequestQueue == null) {
eRequestQueue = Volley.newRequestQueue(context);
eRequestQueue.add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String temp = response.substring(2, response.length() - 2);
Log.d("API", "Current menu" + response);
byte msgArray[];
try {
msgArray = temp.getBytes("ISO-8859-1");
currentMenu = msgArray[0];
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
menuInformation = response;
callback.onSuccess(menuInformation);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("API", "Current menu Nope ");
callback.onFailure(error);
}
}));
}
}
Main Activity:
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu",
MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("NSD", "Current menu response succeded and added to array " + nsdServiceInfo);
//services.add(myPrinterDetails);
mAdapter.notifyDataSetChanged();
}
});
Log.d("NSD", "CurrentMenu " + myPrinterDetails.getMenuInformation());
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu", MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
Log.d("NSD", "Current menu response added to timer " + nsdServiceInfo);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu timer failed");
}
});
}
});
}
}, 0, 2000);
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu response failed");
}
});
}
};
}

how to make generic retrofit library for api calling

i'm working on API integration. i want to make generic class for API integration. which can comfortable with for all API integration.right now i'm using separate code for all API. i'm new in android application development. so please guide me.
public void getHomeCategoryDetailApi(Context context) {
final ProgressDialog loadingDialog = ProgressDialog.show(context, "Please wait", "Loading...");
Retrofit restAdapter = ApiLists.retrofit;
ApiLists apiCall = restAdapter.create(ApiLists.class);
Call<HomeCategoryModelClass> call = apiCall.homePageCatListAPI();
Log.d(TAG, "CategoryDetail : " + call.request()+" \n"+apiCall.homePageCatListAPI().toString());
call.enqueue(new Callback<HomeCategoryModelClass>() {
#Override
public void onResponse(Call<HomeCategoryModelClass> call, Response<HomeCategoryModelClass> response) {
Log.d(TAG, "onResponse: CategoryDetail:" + response.body());
Log.d(TAG, "onResponse: response.code():" + response.code());
if (response.body() == null) {
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
} else {
loadingDialog.dismiss();
if (response.body().getStatusCode().equalsIgnoreCase("1")) {
homeCategoryImageMenu = (ArrayList<Menu>) response.body().getMenu();
thirdHorizontalRecyclerAdapter.notifyDataSetChanged();
} else {
globalClass.showAlertDialog(getActivity(), "Alert", "" + response.body().getStatus(), false);
}
}
if (response.errorBody() != null) {
try {
Log.d(TAG, "onResponse: response.errorBody()===>" + response.errorBody().string());
if (loadingDialog.isShowing() && loadingDialog != null) {
loadingDialog.dismiss();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<HomeCategoryModelClass> result, Throwable t) {
Log.d(TAG, "onFailure: " + result.toString());
loadingDialog.dismiss();
globalClass.showAlertDialog(getActivity(), getString(R.string.InternetAlert), getString(R.string.InternetMessage), false);
}
});
}
Here is Bast Way to call API
public class APIResponse {
private static String TAG = APIResponse.class.getSimpleName();
public static <T> void callRetrofit(Call<T> call, final String strApiName, Context context, final ApiListener apiListener) {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.show();
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
if (strApiName.equalsIgnoreCase("LoginApi")) {
if (response.isSuccessful()) {
Log.d(TAG, "onResponse: " + response.body().toString());
// NearByNurse nearByNurse = (NearByNurse) response.body(); // use the user object for the other fields
// apiListener.success(url,nearByNurse);
progressDialog.dismiss();
} else {
try {
Log.d(TAG, "onResponse: " + response.errorBody().string());
apiListener.error(strApiName, response.errorBody().string());
progressDialog.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
} else if (strApiName.equalsIgnoreCase("")) {
//Patient user = (Patient) response.body();
}
}
#Override
public void onFailure(Call<T> call, Throwable t) {
Log.d(TAG, "onFailure: " + t.toString());
if (strApiName.equalsIgnoreCase("searchNearbyTest")) {
apiListener.failure(strApiName, t.toString());
}
progressDialog.dismiss();
}
});
}
In API Calling Side
private void loginApi() {
Retrofit retrofit = ApiLists.retrofit;
ApiLists apiList = retrofit.create(ApiLists.class);
Call<JsonElement> loginApiCall = apiList.loginApi("kjdf", "fkldngdkl", "lkfdxngl", "kjngn", "jksdgkj");
APIResponse.callRetrofit(loginApiCall, "LoginApi", LoginActivity.this, this);
}
#Override
public void success(String strApiName, Object response) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void error(String strApiName, String error) {
if (strApiName.equals("LoginApi")) {
}
}
#Override
public void failure(String strApiName, String message) {
if (strApiName.equals("LoginApi")) {
}
and interface call on API response.
public interface ApiListener {
void success(String strApiName, Object response);
void error(String strApiName, String error);
void failure(String strApiName, String message);
}
This's my common function basic call Api.java
public class Api {
private void basicCall(Call<DataResponse> call) {
if (call == null) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
return;
}
call.enqueue(new Callback<DataResponse>() {
#Override
public void onResponse(#NonNull Call<DataResponse> call, #NonNull Response<DataResponse> response) {
int code = response.code();
//Check http ok
if (code == HttpURLConnection.HTTP_OK) {
//Check status
if (response.body().getStatus() == Config.STATUS_OK) {
//Everything's OK
listener.onResponseCompleted(Config.STATUS_OK, response.body().getError(), response.body().getData());
} else {
listener.onResponseCompleted(Config.STATUS_FAILED, response.body().getError(), null);
}
} else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
try {
ErrorResponse error = Api.gson.fromJson(response.errorBody().string(), ErrorResponse.class);
listener.onResponseCompleted(Config.STATUS_401, error.getError(), error.getData());
} catch (IOException e) {
e.printStackTrace();
}
} else {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
}
#Override
public void onFailure(#NonNull Call<DataResponse> call, #NonNull Throwable t) {
listener.onResponseCompleted(Config.STATUS_404, "404 not found", null);
}
});
}
//And you can use
public void getProductList(OnResponseCompleted listener) {
this.listener = listener;
Call<DataResponse> call = apiService.getProductList();
basicCall(call);
}
}
//or orther function
This's ApiService.java
public interface ApiInterface {
#POST("product/list")
Call<DataResponse> getProductList();
}
This's OnResponseCompleted.java
public interface OnResponseCompleted {
void onResponseCompleted(int status, String error, Object data);
}
i want to make like this .i just pass some require parameter....
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
// Set Dialog Message
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
if (status != null)
// Set alert dialog icon
alertDialog.setIcon((status) ? R.drawable.ic_success : R.drawable.ic_fail);
// Set OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Show Alert Message
alertDialog.show();
}
Try this code..
In this code Retrofit object set up done in one class and all api calling into interface..
public class ApiClient {
private final static String BASE_URL = "https://api.github.com";
public static ApiClient apiClient;
private Retrofit retrofit = null;
public static ApiClient getInstance() {
if (apiClient == null) {
apiClient = new ApiClient();
}
return apiClient;
}
//private static Retrofit storeRetrofit = null;
public Retrofit getClient() {
return getClient(null);
}
private Retrofit getClient(final Context context) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.readTimeout(60, TimeUnit.SECONDS);
client.writeTimeout(60, TimeUnit.SECONDS);
client.connectTimeout(60, TimeUnit.SECONDS);
client.addInterceptor(interceptor);
client.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
}
after that call the api into api interface..
public interface ApiInterface {
#GET("{affenpinscher}/images")
Call<Product> getProductData(#Path("affenpinscher") String breed);
#GET("getProductDetailByProductId?ProductId=3")
Call<JsonObject> ITEM_DESCRIPTION_RESPONSE_CALL();
#POST("linke")
Call<Response> passJsonData(#Body JsonData jsonData);
#GET("/users/waadalkatheri/repos")
Call<Response> getdata();
}
and when you call api in activity or fragment used below code..
ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
Call<ResponseData> responseCall = apiInterface.getdata();
responseCall.enqueue(new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
if (response.isSuccessful() && response.body() != null && response != null) {
Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
Log.d("Errror", t.getMessage());
}
});

Unable to send post request with volley android like ajax

I have a problem with volley, I googled around for samples to upload the image
with volley, however, since I'm a beginner, I have a hard time trying to make my code that works in
ajax into android (Trying to do the eact same thing with volley). The following code is what I want to do with android
volley Multipart. Some tips or examples will be great. I would love to hear from you!
$.ajax({
type: 'post',
processData: false,
contentType: false,
data: "/imagepath/sample.PNG",
url: "https://linktotheimageuploader/upload",
async: true,
success: function (res) {
if (res.status == 0) {
console.log(res);
} else {
// NOP
}
}
, error: function () {
//failed to upload
}
});
I tried to convert it to Volley android like the following but I am unable to achieve what I want to do.
public void uploadImage(String url , final File fileName) {
final File encodedString = fileName;
RequestQueue rq = Volley.newRequestQueue(this);
Log.d("URL", url);
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
Log.e("RESPONSE", response);
JSONObject json = new JSONObject(response);
Toast.makeText(getBaseContext(),
"The image is upload" +response, Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
Log.d("JSON Exception", e.toString());
Toast.makeText(getBaseContext(),
"Error while loadin data!",
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR", "Error [" + error + "]");
Toast.makeText(getBaseContext(),
"Cannot connect to server", Toast.LENGTH_LONG)
.show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(encodedString); // I want to set the file not a String,
return params;
}
};
rq.add(stringRequest);
}
First, To get callBack from the server in MultipartUploadRequest, create a class by extending the UploadServiceBroadcastReceiver
public class SingleUploadBroadcastReceiver extends UploadServiceBroadcastReceiver {
public interface Delegate {
void onProgress(int progress);
void onProgress(long uploadedBytes, long totalBytes);
void onError(Exception exception);
void onCompleted(int serverResponseCode, byte[] serverResponseBody);
void onCancelled();
}
private String mUploadID;
private Delegate mDelegate;
public void setUploadID(String uploadID) {
mUploadID = uploadID;
}
public void setDelegate(Delegate delegate) {
mDelegate = delegate;
}
#Override
public void onProgress(String uploadId, int progress) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(progress);
}
}
#Override
public void onProgress(String uploadId, long uploadedBytes, long totalBytes) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onProgress(uploadedBytes, totalBytes);
}
}
#Override
public void onError(String uploadId, Exception exception) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onError(exception);
}
}
#Override
public void onCompleted(String uploadId, int serverResponseCode, byte[] serverResponseBody) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCompleted(serverResponseCode, serverResponseBody);
}
}
#Override
public void onCancelled(String uploadId) {
if (uploadId.equals(mUploadID) && mDelegate != null) {
mDelegate.onCancelled();
}
}
}
Then, in your activity:
public class YourActivity extends Activity implements SingleUploadBroadcastReceiver.Delegate {
private static final String TAG = "AndroidUploadService";
private final SingleUploadBroadcastReceiver uploadReceiver =
new SingleUploadBroadcastReceiver();
#Override
protected void onResume() {
super.onResume();
uploadReceiver.register(this);
}
#Override
protected void onPause() {
super.onPause();
uploadReceiver.unregister(this);
}
public void uploadMultipart(final Context context) {
try {
String uploadId = UUID.randomUUID().toString();
uploadReceiver.setDelegate(this);
uploadReceiver.setUploadID(uploadId);
new MultipartUploadRequest(context, uploadId, "http://upload.server.com/path")
.addFileToUpload("/absolute/path/to/your/file", "your-param-name")
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
} catch (Exception exc) {
Log.e(TAG, exc.getMessage(), exc);
}
}
#Override
public void onProgress(int progress) {
//your implementation
}
#Override
public void onProgress(long uploadedBytes, long totalBytes) {
//your implementation
}
#Override
public void onError(Exception exception) {
//your implementation
}
#Override
public void onCompleted(int serverResponseCode, byte[] serverResponseBody) {
//your implementation
}
#Override
public void onCancelled() {
//your implementation
}
}
I have done this with Volley in two different ways:
Sending the image as a Base64 encoded string
Sending the image as multipart
Sending it as encoded String
This method will encode a bitmap into a Base64 String which you can send as a parameter in your request. Then, the server can decode the String back to an image.
public String bitmapToString(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("image", bitmapToString(BitmapFactory.decodeFile(filePath)));
return params;
}
};
Sending it as Multipart
This is a little bit more tricky since you'll need to use custom classes made by some dude named anggadarkprince, but it's way faster than the first option
VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, url, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
RandomAccessFile f = null;
try {
f = new RandomAccessFile(filePath, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
byte[] b;
try {
b = new byte[(int)f.length()];
f.readFully(b);
} catch (IOException e) {
e.printStackTrace();
return null;
}
params.put("image", new DataPart("image.jpg", b, "image/jpeg"));
return params;
}
};
Here you'll find the class you need to do this.

Android JobScheduler API

I am sending a request to a server using Volley in a JobService. My question is, since the service runs on the main thread, should I create a seperate thread inside the service and call my Volley request there, or simple call the volley request? Here is some of my code.
public class JobService extends android.app.job.JobService {
static int count = 0;
#Override
public boolean onStartJob(final JobParameters jobParameters) {
Log.d("Job Service", "onStartJob " + count);
final SharedPreferences prefs = getSharedPreferences(LOGIN_PREFS, MODE_PRIVATE);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Job Service", "onResponse");
try {
writeFileToCache(response);
jobFinished(jobParameters, true);
} catch (Exception e) {
e.printStackTrace();
jobFinished(jobParameters, true);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley error job", error.toString());
jobFinished(jobParameters, true);
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("regno", prefs.getString(REG_NO, ""));
params.put("bdate", prefs.getString(DATE_OF_BIRTH, ""));
return params;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(12000, 0, 0f));
queue.add(request);
return true;
}
private void writeFileToCache(String response) throws IOException {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
return;
}
File file = new File(getExternalCacheDir() + CACHE_FILE);
FileOutputStream fout = new FileOutputStream(file);
Log.d("Writing to cache job", response);
fout.write(response.getBytes());
fout.close();
}
#Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d("Job Service", "onStopJob");
return false;
}

How to use Call Type with EventBus

I am using EventBus to notify Activity/Fragment when I get response from the server. Everything works good so far, but problem arises when I consume two network calls in same Fragment or Activity. The problem is the same method onEvent(String response) get calls for both responses from server. The response of call 1 is different from call 2.
I came up with a solution - I added CallType in NetworkReqest but I can't notify the activity/fragment about the network call since post() takes only one parameter.
Here is the relevant code -
public class NetworkRequest {
EventBus eventBus = EventBus.getDefault();
public void stringParamRequest(String url, final Map<String, String> params,String callType) {
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
eventBus.post(error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = params;
return param;
}
};
SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
}
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
}
Method Inside the fragment/activity Here arise the problem when after getting the response from one request i fire another request which is dependent of the respose of the first request
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(String response) {
Log.d(TAG, response);
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
isCourseAvaible = true;
List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
} else {
Log.d(TAG, response);
}
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(VolleyError error) {
Log.d(TAG, error.toString());
Toast.makeText(getActivity(), "Something went wrong " + error.toString(), Toast.LENGTH_SHORT).show();
}
How can I differentiate the callType within onEvent(). Some guidance is required. Thanks much.
One option is to wrap the two pieces of data you need into a class and pass that to event bus. Leaving off private members, getters/setters and constructors for brevity.
class NetworkResponse() {
public String callType;
public String response;
}
When you get a response, allocate a NetworkResponse and populate it with the response and the call type and post that to the event bus.
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(NetworkResponse networkResponse) {
if(networkResponse.callType.equals(CALL_1)) {
// ...
} else if (networkResponse.callType.equals(CALL_2)) {
// ...
}
}
Serialize the String response to a java bean in the onResponse method, and emit the right object to the views. Activities, Fragments and Views have no need to know about serialization, and besides, your app's performance can improve, since you can modify your code to serialize the data in a background thread.
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(AppMgr.coursesMgr(response));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
Then your first event subscription will look like this:
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(List<CoursesDTO> coursesDTOs) {
Log.d(TAG, response);
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
isCourseAvaible = true;
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
} else {
Log.d(TAG, response);
}
}
and you can have a second, different, String subscription. But since you are going to make the second call anyway, it would be best to execute it directly after getting the right answer from the first one.
public class NetworkRequest {
EventBus eventBus = EventBus.getDefault();
public void stringParamRequest(String url, final Map<String, String> params,String callType) {
StringRequest jsonObjRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
eventBus.post(response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("volley", "Error: " + error.getMessage());
eventBus.post(error);
}
}) {
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> param = params;
return param;
}
};
SkillSchoolApplication.get().addToRequestQueue(jsonObjRequest);
}
public void stringRequest(String url, String callType) {
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
List<CoursesDTO> coursesDTOs = AppMgr.coursesMgr(response);
String[] ids = new String[0];
String id;
if (coursesDTOs != null) {
ids = new String[coursesDTOs.size()];
for (int i = 0; i < coursesDTOs.size(); i++) {
ids[i] = coursesDTOs.get(i).getListId();
}
}
id = TextUtils.join(",", ids);
Map<String, String> map = new HashMap<>();
map.put("part", "snippet,contentDetails");
map.put("playlistId", id);
map.put("key", AppConstants.YOUTUBE_KEY);
NetworkRequest networkRequest = new NetworkRequest();
networkRequest.stringParamRequest("some url", map);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
SkillSchoolApplication.get().addToRequestQueue(stringRequest);
}
}
Finally, this two lines
boolean isCourseAvaible = false;
if (!isCourseAvaible) {
are superfluous, is like having no condition.

Categories

Resources