How to get callback value Outside the function - android

I am using volley library and have made a callback but after getting the result in callback. How should I assign it to another variable and use in same activity.
IResult getResult = new IResult()
{ #Override
public void notifySuccess(String requestType, String response) {
}
#Override
public void notifyError(String requestType, VolleyError error) {
}
};

You can define variable in your activity and assign it from callback.
if you want to update view from this result you can call method from result callback.
String apiResult=null;
IResult getResult = new IResult()
{ #Override
public void notifySuccess(String requestType, String response) {
apiResult=response
//or call method for update UI
}
#Override
public void notifyError(String requestType, VolleyError error) {
//or call method for update UI
}
};
Hope this will help you.

Related

OnResponse Callback Not trigger

in retrofit Client When Create data OnResponse Not Call
but Passing In the database
I cant intern in Another Activity.
public void saveUser(StudentName studentName){
Call<StudentName>call =ApiClient.getStudentName().sendStudentName(studentName);
call.enqueue(new Callback<StudentName>() {
#Override
public void onResponse(Call<StudentName> call, Response<StudentName> response) {
Intent intent = new Intent(StudentData.this,MainActivity.class);
startActivity(intent);
}
#Override
public void onFailure(Call<StudentName> call, Throwable t) {
}
});

How to return String from onResponse? Retrofit android studio

I've seen a few similar questions but they don't seem to answer my problem exactly. I've got a method that is supposed to return a string. I am using retrofit, but in onresponse, I can't return a string? Below is the code.
public String getInformation(String information, String username) {
String result;
Call<DefaultResponse> call = RetrofitClient.getInstance().getApi().getInformation(information,username);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
result = response.body().getMsg();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
}
});
return result;
}
The .enqueue method will take time to get the response, so your method will return before onResponse callback gets called.
Try using a callback approach for getInformation method and make it void:
public void getInformation(String information, String username, MyCallback callback) {
Call<DefaultResponse> call = RetrofitClient.getInstance().getApi().getInformation(information,username);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
result = response.body().getMsg();
callback.success(result);
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
callback.failure(t)
}
});
}
With the MyCallback interface:
interface MyCallback {
void success(String result);
void failure(Throwable t);
}
Then you can call the method like this:
getInformation("Information", "Username", new MyCallback() {
#Override
public void success(String result) {
// Use result
}
#Override
public void failure(Throwable t) {
// Display error
}
});
You can use Result as output String wherever you want, as I used it in my adapter class in onBindViewHolder method, simply making object of the class from which string was sent and then calling the method (in which Interface was kept as parameter) & override success and failure method in adapter class and do whatever u want to do with this string......... Thanks a lot #y.allam & #Anonymous Cardinal :):)

onNext not called - RxJava

I'm using RxAndroid for my app to send a request to the backend and handle the result.
public Observable<Response> getBrands() {
return new Observable<Response>() {
#Override
protected void subscribeActual(Observer<? super Response> observer) {
RequestHelper.GetRequest("getbrands");
}
};
}
public void GetBrands(){
getBrands().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Response>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(Response value) {
Log.w("Reactive",value.toString());
Toast.makeText(getActivity(),"Yaaaaay request 5alas",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(Throwable e) {
Log.w("response brands= "+e.toString(),"MyTAG");
}
#Override
public void onComplete() {
}
});
}
RequestHelper.GetRequest("getbrands") is successfully called (Checked backend logs, it's called and returns the response.
the problem is onNext not getting called at all, neither the log or the toast shows up.
Anyone knows why ?
EDIT: i'm using this in a fragment where GetBrands() is called in oncreateview
Just changed my observable function to
public Observable<Response> getBrands() {
return Observable.fromCallable(new Callable<Response>() {
#Override
public Response call() throws Exception {
return RequestHelper.GetRequest("getbrands");
}
});
}
it's working now

ProgressDIalog freezing during load data from Retrofit + RxJava

I am using a ProgressDialog to be presented before making a Rest request using Retrofit + RxJava, the response of the request is large and this is freezing the animation of ProgressDialog. How can I fix this? I only found examples saying to use runOnUiThread or the doInBackground with AsyncTask but, I'm using RxJava. I tried the runOnUiThread but it did not work.
//My request
public void getMyData(final MyListener listener) {
AppApi AppApi = getInstanceMyApi();
AppApi.getMyData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseData>() {
#Override
public void onCompleted() {
}
#Override
public void onError(Throwable e) {
//error
}
#Override
public void onNext(ResponseData response) {
//success, send data to presenter to update view
}
});
//Presenter call ws
public void attemptGetDataFromWS() {
showProgress();
getMyData(this);
}
#Override
public void onGetMyDataSuccess(ResponseData response) {
hideProgress();
}
#Override
public void onGetMyDataError(String error) {
hideProgress();
}
public void getMyData(final MyListener listener) {
AppApi AppApi = getInstanceMyApi();
AppApi.getMyData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableObserver<ResponseData>() {
#Override
public void onCompleted() {
dispose();
}
#Override
public void onError(Throwable e) {
listener.onGetMyDataError(e.getMessage());
}
#Override
public void onNext(ResponseData response) {
listener.onGetMyDataSuccess(response);
}
});
//Presenter call ws
public void attemptGetDataFromWS() {
showProgress();
getMyData(this);
}
#Override
public void onGetMyDataSuccess(ResponseData response) {
hideProgress();
}
#Override
public void onGetMyDataError(String error) {
hideProgress();
}
Follow this method .this is calling example with REST API + Retrofit
private void callRestAPI() {
Retrofit retrofit = new Retrofit.Builder().baseUrl(BASEURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
newsAPI = retrofit.create(NewsAPI.class);
Call<JSONResponse> call = newsAPI.topNews("soure", "api-key");
// Set up progress before call
final ProgressDialog progressDoalog;
progressDoalog = new ProgressDialog(MainActivity.this);
progressDoalog.setMax(100);
progressDoalog.setMessage("Its loading....");
progressDoalog.setTitle("ProgressDialog bar example");
progressDoalog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// show it
progressDoalog.show();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
// close it after response
progressDoalog.dismiss();
}
}
#Override public void onFailure (Call < JSONResponse > call, Throwable t){
// close it after response
progressDoalog.dismiss();
}
});
}

Handle onResume in fragment

I have a fragment where I post request to server. This type of action should be in onResume() method, but I don't want to post request to server every time when I put app on background. Is exist any solution?
request which I want to post
FactoryAPI.getContacts().getContacts(user.getToken()).enqueue(new Callback<ContactsResponse>() {
#Override
public void onResponse(Call<ContactsResponse> call, Response<ContactsResponse> response) {
if(response.isSuccessful()) {
contactList = response.body().getContactsList();
sortList();
progressDialog.dismiss();
setRecyclerView();
}
}
#Override
public void onFailure(Call<ContactsResponse> call, Throwable t) {}
});
In your Fragment class, create a data member of type boolean like,
private boolean isResponseSend;
In your onResume() method,
#Override
public void onResume() {
super.onResume();
if(!isResponseSend)
{
isResponseSend = true;
//your code
FactoryAPI.getContacts().getContacts(user.getToken()).enqueue(new Callback<ContactsResponse>() {
#Override
public void onResponse(Call<ContactsResponse> call, Response<ContactsResponse> response) {
if(response.isSuccessful()) {
contactList = response.body().getContactsList();
sortList();
progressDialog.dismiss();
setRecyclerView();
}
}
#Override
public void onFailure(Call<ContactsResponse> call, Throwable t) {}
});
}
}
According to
https://developer.android.com/guide/components/fragments.html#Creating
you can post the request on
https://developer.android.com/reference/android/app/Fragment.html#onAttach(android.content.Context)
Use some variable like flag, and initialise it in the onCreate. and based on the flag, you can handle the request.

Categories

Resources