I am just now learning about Retrofit 2. In my app Intent "UploadToServer"
I have three async tasks that I need to call sequentially:
1. Post UserName and get back UserId.
2. Post Geolocation and some other string data and get back a "report ticket number".
3. Post a jpg image along with the ticket number.
I have a web service running on my server.
In standard hand-coded Java I would use a looper or something equivalent.
How could this be accomplished using Retrofit 2? And oh, I would like to have a progress bar moving, especially when uploading the jpg image file.
Thanks.
You can chain the calls using the callbacks:
OkHttpClient client = new OkHttpClient.Builder().build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL_WEBAPI)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
mService = retrofit.create(IWebApi.class);
...
mService.first_operation(...params...).enqueue(callback);
callback is an instance of a class that expects the results of first_operation. If first_operation success, then call the second_method.
public class Example implements Callback<void> {
#Override
public void onResponse(Response<LoginResponse> response) {
second_method();
}
#Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}
Hope it helps.
Edit:
I use a ProgressDialog with indeterminated in true. You can show it right before the call to the service and hide when a response arrives, in the onResponse or in the onFailure methods.
mProgressDialog = ProgressDialog.show(this, getString(R.string.wait_plaease),
getString(R.string.executing_action), true);
Related
I really need help!
I have a server that sends me predicting time. I need to send request to the server every 10 minutes(even if the app closed) and ask the current time. if the time changed I need to make a notification to the client.
the stop trigger is if the predicting time is now.
so - I have ClientActivity and I have the code to communicate the server.
How can I do that?
Thanks a lot!
public interface APIClient {
#POST("/api/post_some_data")
Call<PostResponse> getPostRequest(#Body PostRequest body);
}
public class NetworkClient {
public static final String BASE_URL = "http://*****:8080";
public static Retrofit retrofit;
/*
This public static method will return Retrofit client
anywhere in the appplication
*/
public static Retrofit getRetrofitClient() {
//If condition to ensure we don't create multiple retrofit instances in a single application
if (retrofit == null) {
//Defining the Retrofit using Builder
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL) //This is the only mandatory call on Builder object.
.addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
.build();
}
return retrofit;
}
}
I am trying to send the converted file (Base64 - String) as a parameter in POST, the file is about 8 MB, but sending takes about 4 minutes. Is there a way to speed up?
Interface:
#FormUrlEncoded
#POST("upload")
Call<Upload> upload(#Field("CONTENT") String content);
Retrofit instance:
public class RetrofitClientInstance {
private static Retrofit retrofit;
private static OkHttpClient client;
public static Retrofit getRetrofitInstance(String url) {
if (retrofit == null && !url.isEmpty()) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
retrofit = new retrofit2.Retrofit.Builder()
.baseUrl(url)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
Call:
private void upload(){
Api api = RetrofitClientInstance.getRetrofitInstance(SharedUtils.SERVER_URL).create(Api.class);
Call<Upload> request = api.upload(getBase64FromFile());
request.enqueue(new Callback<Upload>() {
#Override
public void onResponse(Call<Upload> call, Response<Upload> response) {
}
#Override
public void onFailure(Call<Upload> call, Throwable t) {
}
});
}
Try to compress your file or image before uploading, because it would take so much time to make it done
First of all, you are using enqueue() method of retrofit which is an asynchronous way of executing the code and you have registered callbacks to these methods on successful execution you will receive the call inside onResponse() method but on failure, you will get control inside the onFailure() method.
This will spawn a thread of execution from the daemon thread which creates another thread of execution you may never know when will this thread gets executed based on OS priority.
Use execute() method to execute this in a synchronous manner and then check the response time it would give a proper result.
I have AsyncTask and the doInBackground method inside which, I sending POST request using Retrofit. My code looks like:
//method of AsyncTask
protected Boolean doInBackground(Void... params) {
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(Constants.ROOT_API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
IConstructSecureAPI service = restAdapter.create(IConstructSecureAPI.class);
//request
Call<JsonElement> result = service.getToken("TestUser", "pass", "password");
result.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
}
});
return true;
}
The problem is: Retrofit sending request asynchronously and while it, the doInBackground method returning the value. So I need to send a request in the same thread with all executions in the sequence. One by one. And returning from doInBackground occurs after the request finished. How can I send a request in the same thread using Retrofit?
The Call class has an execute() method that will make your call synchronously.
enqueue() is explicitly for making an asychronous call.
"Retrofit sending request asynchronously" which as #Tanis.7x mentioned, enqueue() is doing the asynchronous, so what could be a reason to put in AsyncTask ? (async in async ?)
You can simply put all retrofit code out from AsyncTask and onResponse is the callback that is waiting for your request call to be back, so you can do any UI update inside of this callback.
Use retrofit execute method instead of the enqueue method.
Because in asynctask doInbackground method is already creating a thread to execute the code in background. No need to create it again using retrofit enqueue.
I have downloaded the retrofit library and samples from https://github.com/square/retrofit.I want to do image and data caching.
But I am not getting how to use that in android.Can Somebody give me an example.I have checked the code
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("")
.build();
ClientInterface service = restAdapter.create(ClientInterface.class);
Callback callback = new Callback() {
#Override
public void success(Object o, Response response) {
// Read response here
}
#Override
public void failure(RetrofitError retrofitError) {
// Catch error here
} };
service.findBuffet("sudhakar", callback);
But I am not getting anything.
Thanks for the help in advance...
You have to create an interface like below.
public interface MyService {
#GET("/getUser/{user}")
User getUserDetails(#Path("user") String userId);
}
Create your rest adapter
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://mybaseurl.com")
.build();
MyService service = restAdapter.create(MyService.class);
Get user details like this:
User user = service.getUserDetails("123456");
To get a successful result you have to define your pojos correctly.
You can use this link to create your pojos : http://www.jsonschema2pojo.org/
Retrofit is best to use. follow are the steps to use retrofit.
Please get details process here
Step 1- add dependency
Step 2 - init retrofit and add wrapper functions to call interface
Step 3 - Create POJO model using any online jsoneditor like jsoneditor.org
Step 4 - Create interface (URL from where you want to fetch date)
Step 5 - Call wrapper function from activity.
I am working on an Android App, in which I need to make a lot of http queries. Since Android has a constrain to prevent program making http request on UI thread, I have to use a lot of Async methods to get response from the server. I am not a guru of using callbacks, there's a code design problem I am facing now:
Basically, I have a activity to display. I want the app to make a HttpRequest to server when the activity is created, so I can prepare the content of the activity based on the query response.
Since I am using the Google Volley library to make http requests, my code design is:
// in the Activity
OnCreate(Bundle b){
String response = RequestManager.makeRequest(args);
// other works based on the response in this activity.
}
// RequestManager Class
public static String makeRequest(args){
String url = getUrl();
// response callback
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Don't know what to do here
}
};
// error callback
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// deal with errors
}
};
BuildRequestAndPushToQueue(url, responseListener, errorListener);
// No way to return the response!
}
I know my design is totally incorrect, because String response = RequestManager.makeRequest(args); is intent to wait for a blocking call, but the call is actually async.
My ultimate goal is to let the response String returned to some code in the activity, so it can use the activity context to do the rest works (like access to a imageview, etc). But I am not sure how to design the code flow to make this happen.