how to get response toast - android

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(uri)
.addConverterFactory(GsonConverterFactory.create())
.build();
ayapi api = retrofit.create(ayapi.class);
Call<model> call = api.adddata(namevalue,numbervalue,emailvalue,countryvalue,statevalue,cityvalue,pincodevalue,addressvalue,teams);
call.enqueue(new Callback<model>() {
#Override
public void onResponse(Call<model> call, Response<model> response) {
Toast.makeText(getApplicationContext(),"Inserted",Toast.LENGTH_LONG).show();
finish();
startActivity(new Intent(getApplicationContext(),home.class));
}
#Override
public void onFailure(Call<model> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});

You are running background work so you can not run toast like that
instead, you can do this:
ayapi api = retrofit.create(ayapi.class);
// define toast before calling background work
Toast toast =
Toast.makeText(getApplicationContext(),"Inserted",Toast.LENGTH_LONG);
Call<model> call = api.adddata(namevalue,numbervalue,emailvalue,countryvalue,statevalue,cityvalue,pincodevalue,addressvalue,teams);
call.enqueue(new Callback<model>() {
#Override
public void onResponse(Call<model> call, Response<model> response) {
//call toast here
toast.show();
finish();
startActivity(new Intent(getApplicationContext(),home.class));
}
#Override
public void onFailure(Call<model> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});

you can get Data from response.body() like this
Toast.makeText(getApplicationContext(),"Inserted" + response.body(),Toast.LENGTH_LONG).show();

Related

I keep connection failed error in my "onFailure" method

I'm using retrofit object to call my API but I keep getting
"java.net.ConnectException: Failed to connect to
api.backtory.com/185.105.185.244:443"
in my onFailure method
I have set the title using #Headers
I have added INTERNET permission to my manifests
I have added the gson-converter library and retrofit as well
public class RegisterUserController {
public void start(User user){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ChatRoomAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ChatRoomAPI chatRoomAPI = retrofit.create(ChatRoomAPI.class);
Call<User> call = chatRoomAPI.registerUser(user);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
Log.d("TAG" , "onResponse" + response.code());
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.d("TAG" , "onFailure" + t.getCause()); //
}
});
}
}

Retrofit 2 How to Make Same Request Multiple Times

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

Retrofit return boolean value

I want to run changesHasBeenSaved if saveChanges function gives me true value.
How can I get boolean or string or integer, any value, when Retrofit finish?
Is it possible?
I need a function similar this:
public boolean saveChanges()
{
Boolean output = false;
RequestAPI requestAPI = Requests.getRetrofit();
Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();
jsonObjectCall.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
if(response.body() != null) {
output = true;
}
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
}
});
return output;
}
You should change method return type boolean to void as retrofit work asynchronous.
You should pass the listener/callback to get the status in callback.
First create callback interface like below
public interface ApiCallback {
void onResponse(boolean success);
}
Here how saveChanges will look like
public void saveChanges(final ApiCallback callback)
{
RequestAPI requestAPI = Requests.getRetrofit();
Call<Object> jsonObjectCall = requestAPI.readAllCategoeies();
jsonObjectCall.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
callback.onResponse(response.body() != null);
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
callback.onResponse(false);
}
});
}
Then you need to call saveChanges method like below
saveChanges(new ApiCallback () {
public void onResponse(boolean success){
if(success){
// do something
} else{
// do something
}
}
});
jsonObjectCall.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
//when the response is successful
if(response.isSuccessful()) {
output = true;
// display response as string
Log.i(TAG, "post submitted to API." + response.body().toString());
//Object user1 = response.body(); maps response to the modal class
}
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
call.cancel();
}
})
Change you call back to like the above , included comments for clearity about usage .
Hope this helps.

Android - Retrofit does not display data

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.

How to set Value which is get from Common class(retrofit)

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
}

Categories

Resources