Condition: I've a button. When user click the button (example ADD NEW NAME button) so the data will send to server.
I've question: How to add new data to server?
What should I put into onResponse and onFailure based on this code:
private void sendDataToServer() {
APIClient client = ServiceGenerator.createService(APIClient.class);
Call<ResponseBody> result = client.addNewName(etName.getText().toString(),
etEnglish.getText().toString(),
etGender.getText().toString());
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Response<ResponseBody> response) {
}
#Override
public void onFailure(Throwable t) {
}
}
);}
*et - Edit Text
Thanks.
Related
public void makeGetRequest() {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success" , " " + response.body().bytes().length);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
I have this code and it makes a get request to my server with the async method. What I want is to make the same request multiple times. For example, I want to make get request 100 times. I don't want to use observables or other external libraries if possible. Is there anyone who can help me with that?
You can make call multiple times just see the below code where I have used methods for this purpose. In onResponse method after performing operation on data you get from server you can make another call to the same API by using a variable sizeOfCall and decrementing it untill it equals to zero. Below is the full code for it.
public class RequestActivity extends AppCompatActivity {
int sizeOfCall = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
callAPI();
}
private void callAPI(){
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
// Call API
makeGetRequest(call);
}
private void makeGetRequest(Call<ResponseBody> call) {
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success", " " + response.body().bytes().length);
// Perform your operations here and call API againg after that
sizeOfCall--;
if (sizeOfCall > 0) {
callAPI();
} else {
// No more calls needed
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
}
}
Create a broadcast reciever and put your retrofit request in that. Now call it using alarm manager.
public class YourBroadCastReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
yourRetrofitCode();
}
private void yourRetrofitCode(){
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://desolate-beach-17272.herokuapp.com");
Retrofit retrofit = builder.build();
RetrofitInterface retrofitInterface = retrofit.create(RetrofitInterface.class);
Call<ResponseBody> call = retrofitInterface.downloadFileByUrl("downloadFile/beach.jpg");
call.enqueue(new Callback<ResponseBody>() {
#SuppressLint("StaticFieldLeak")
// returns the response if everything is okay
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
try {
Log.d("Success" , " " + response.body().bytes().length);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("FAIL", "oops");
}
});
}
}
now call using this code :
Intent sendDeviceInfoIntent = new Intent(this, YourBroadCastReciever.class);
PendingIntent yourintent= PendingIntent.getBroadcast(this, 0, sendDeviceInfoIntent, 0);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+1000, 60000, yourintent);
so that every 5 min this will call your broadcast reciever and this will also works in background
I'm trying to learn Retrofit making simple weather app and I have some problem. I made two methods to display data in Activity and method does not work outside onCreate, but second one in works. In Android Profiler I can see JSON logs, but still I don't see anything in Activity. What's the problem?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WeatherAPI_Interface.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherAPI_Interface weatherAPIInterface = retrofit.create(WeatherAPI_Interface.class);
latitude = 37.8267;
longitude = -122.4233;
Call<Currently> call = weatherAPIInterface.getWeather(latitude, longitude);
call.enqueue(new Callback<Currently>() {
#Override
public void onResponse(#NonNull Call<Currently> call, #NonNull Response<Currently> response) {
temp_textview.setText(String.valueOf(response.body().getCurrently().getTemperature()));
city_textview.setText(response.body().getTimezone());
image_View.setImageResource(Integer.parseInt(response.body().getCurrently().getIcon()));
}
#Override
public void onFailure(#NonNull Call<Currently> call, #NonNull Throwable t) {
}
});
}
#Override
public void getCurrentWeather(final Currently currently) {
latitude = 37.8267;
longitude = -122.4233;
NetworkClient.getInstance().getWeather(latitude, longitude).enqueue(new Callback<Currently>() {
#Override
public void onResponse(#NonNull Call<Currently> call, #NonNull Response<Currently> response) {
weather_textview.setText((CharSequence) response.body().getCurrently().getSummary());
pressure_textview.setText((CharSequence) response.body().getDaily().getData());
temp_textview.setText(String.valueOf(currently.getCurrently().getTemperature()));
Log.d(TAG, "City" + currently.getLatitude());
}
#Override
public void onFailure(Call<Currently> call, Throwable t) {
Log.d(TAG, "Failed" + t.getMessage());
}
});
}
public class NetworkClient {
private static WeatherAPI_Interface service;
public static WeatherAPI_Interface getInstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(WeatherAPI_Interface.API_URL)
.build();
service = retrofit.create(WeatherAPI_Interface.class);
return service;
}
else {
return service;
}
}
}
You didn't call the function how can it work?
when the activity starts it'll run the code in OnCreate ( and any call in it) only, so to run any function outside it you need to call it.
I have fragment and Common class which inside it used retrofit callback..I have Connect_and_get class.It sends request to server and gets information.I must use this information in my fragment.. But I can't return result onResponse.How can I do it..(Response is coming well from server)
Please see my code
public class Connect_and_Get {
private int size;
private OkHttpClient.Builder httpClient;
private ApiService client;
private Call<Response> call;
private MyPreference myPreference;
String a[] = {"secret"};
String b[] = {"secret"};
public int Connect_and_Get() {
Requests request;
request = new Requests("tasks.list", new params(20, 0, a, b, "", "", "", "", ""));
httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder().addHeader("Authorization", "Bearer " + "secret").build();
return chain.proceed(request);
}
});
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
client = retrofit.create(ApiService.class);
call = client.getDocument(request);
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
size = response.body().getResult().getList().size();
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
//retruning information
return size;
}
}
and result from common class coming 0;Because it doesn't wait my response so it is returning 0;
In fragment
Connect_and_Get a = new Connect_and_Get();
int getting = a.Connect_and_Get();
Log.d("mylog", "result:"+String.valueOf(getting));
Declare an interface like this
public interface ResponseListener {
public int onResponse(int size);
}
and use below code in your activity
public class MainActivity extends AppCompatActivity implements ResponseListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Connect_and_Get().Connect_and_Get(this);
}
#Override
public int onResponse(int size) {
// to do
return 0;
}
}
modify your connect class like this
public class Connect_and_Get {
public int Connect_and_Get(ResponseListener responseListener) {
// as it was
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
size = response.body().getResult().getList().size();
responseListener.onResponse(size);
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
}
}
You need to check whether your response is successful or not.
Check the code below.
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
if(response.isSuccessful()){
//enter code here
} else {
//Error Message
}
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
Log.e("Log", "Error -> "+t.getLocalizedMessage());
}
});
You can use an event bus like (rxbus,otto, etc..) to post events across your app when the response from the api ready to use .
Retrofit callback sample code:
call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
Bus.getInstance.post(Event)
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
Fragment sample:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bus.getInstance.register(this)
}
#Subscribe
public void onCallDone(Event response) {
//enter code here
}
I would like to handle my response from server , but I don't know how JSON (from server) its looks like. So I tried to display response as String , but I cant do it. Is it possible to display response as String? And then handle the response correctly. thanks
(Retrofit 1.9)
LoginService loginService = RetrofitClient.createService(LoginService.class);
loginService.searchOffer(getToken(), offerSearch, new Callback<String>() {
#Override
public void success(String offerSearchRequestResource, Response response) {
String responseFromSercer = response.getBody();
}
#Override
public void failure(RetrofitError error) {
}
});
change your response model to
JSONObject (from Gson)
then in your
public void success(...){response.body.toString();}
like this:
Call<JsonObject> call = YOUR_API_INTERFACE().YOUR_METHOD(YOUR_PARAMS);
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, #NonNull Response<JsonObject> response) {
if(response.isSuccessful()) {
String responseFromSercer = response.body.toString();
}
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
.....
}
});
If you are sure the request runs successfully and there is a response back...use
System.out.println(response.getBody());
i'd also suggest you add Logging Interceptors here so that you can get a detailed view of all your API calls
I need make POST request with parameters "guid=1" in Body. i use Retrofit2
I try :
#POST("/api/1/model")
Call<ApiModelJson> getPostClub(#Body User body);
User Class:
public class User {
#SerializedName("guid")
String guid;
public User(String guid ) {
this.guid = guid;
}
MailActivity:
User user =new User ("1");
Call<ApiModelJson> call = service.getPostClub(user);
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response) {
}
#Override
public void onFailure(Throwable t) {
dialog.dismiss();
}
How make this request?
you have to call call.enqueue, providing an instance of Callback< ApiModelJson>, where you will get the response. enqueue executes your backend call asynchronously. You can read more about call.enqueue here
With code below, you can make the request synchronously:
ApiModelJson responseBody = call.execute();
If you want it to be asynchronous:
call.enqueue(new Callback<ApiModelJson>() {
#Override
public void onResponse(Response<ApiModelJson> response, Retrofit retrofit) {
}
#Override
public void onFailure(Throwable t) {
}
});