How to get Json response in retrofit version 2.0.2? - android

I am Using Retrofit v2.0.2. I am not able to get the JSON ResponseI am getting error like this okhttp3.ResponseBody$1#501040a,Please any one help me in this case.
This is Interface:
public interface IdeaInterface {
/*Get zoontype for registeration*/
#GET("api/user/get_zone")
Call<ResponseBody> display();
}
calling retrofit method here.
public void Get_Zoontype()
{
reg_progressbar.setVisibility(View.VISIBLE);
/* RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(Constandapi.ROOT_URL) //Setting the Root URL
.build();*/
// Retrofitnew Retrofit.Builder();
Retrofit adapter = new Retrofit.Builder()
.baseUrl(Constandapi.ROOT_URL)
.build();
IdeaInterface report = adapter.create(IdeaInterface.class);
Call<ResponseBody> call = report.display();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d("reponcevalues","**** "+response.toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is my Base URL:
public class Constandapi {
public static final String ROOT_URL = "http://vehiclerescue.in/ideadarpan_beta/";
}
my build.gradle which has retrofit library
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
Thanks in Advance.

Retrofit code, in It am having Upload Model class.
Call<Uploads> uploadsCall = service.profilePicUpload(body, id);
uploadsCall.enqueue(new Callback<Uploads>() {
#Override
public void onResponse(Call<Uploads> call, Response<Uploads> response) {
response.body();
if (response.isSuccessful()) {
String s = response.body().getMsg();
Communicate.showToast(MyAccountActivity.this, s);
ImageHelper.getImage(MyAccountActivity.this, AppController.ProficPic + profpic, profilePic,
R.drawable.ic_user, R.drawable.ic_user, new ImageHelper.Callback() {
#Override
public void Success() {
runOnUiThread(new Runnable() {
#Override
public void run() {
profpicProgress.setVisibility(View.GONE);
}
});
}
#Override
public void Error() {
runOnUiThread(new Runnable() {
#Override
public void run() {
profpicProgress.setVisibility(View.GONE);
}
});
}
});
} else {
Communicate.showToast(MyAccountActivity.this, "please try again");
profpicProgress.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<Uploads> call, Throwable t) {
profpicProgress.setVisibility(View.GONE);
Communicate.showToast(MyAccountActivity.this, "error");
Log.e(AppController.TAG, "onFailure: " + t.getLocalizedMessage());
Log.e(AppController.TAG, "onFailure: " + t.getMessage());
t.printStackTrace();
}
});
Here i have a model class, I am getting msg and stud_id as json objects
public class Uploads {
#SerializedName("msg")
#Expose
private String msg;
#SerializedName("stud_id")
#Expose
private String stud_id;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getStud_id() {
return stud_id;
}
public void setStud_id(String stud_id) {
this.stud_id = stud_id;
}
}
Hop this will help you

Related

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.

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
}

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());
}
});

Parsing through Retrofit and set Data to the Base Adapter

I am working with Retrofit (JSON Parsing Android) and I am new with this I am so confused to set the response with the Base Adapter.
This is my Example Class
public class Example {
#SerializedName("Totalrecord")
#Expose
private List<Totalrecord> totalrecord = null;
#SerializedName("Table1")
#Expose
private List<Table1> table1 = null;
#SerializedName("Table2")
#Expose
private List<Table2> table2 = null;
public List<Totalrecord> getTotalrecord() {
return totalrecord;
}
public void setTotalrecord(List<Totalrecord> totalrecord) {
this.totalrecord = totalrecord;
}
public List<Table1> getTable1() {
return table1;
}
public void setTable1(List<Table1> table1) {
this.table1 = table1;
}
public List<Table2> getTable2() {
return table2;
}
public void setTable2(List<Table2> table2) {
this.table2 = table2;
}
}
Here I am trying to retrieve Response in ArrayList so that I can set it to Adapter
ApiService api = RetroClient.getApiService();
Call<Example> call = api.getMyJson(38, 109);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
dialog.dismiss();
if (response.isSuccessful()) {
// Response_list = response.body().get...
adapter_view = new Adapter_view(Response_list, MainActivity.this);
listView.setAdapter(adapter_view);
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
dialog.dismiss();
System.out.println("failed");
}
});
But I am confused to set The type of ArrayList and also Type of Callback<> so that I can get the response properly and set ArrayList to the Adapter.
try following if you want to set List<Totalrecord> in your adapter.
ApiService api = RetroClient.getApiService();
Call<Example> call = api.getMyJson(38, 109);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
dialog.dismiss();
if (response.isSuccessful()) {
Response_list.clear();
Response_list.addAll(call.getTotalrecord());
adapter_view = new Adapter_view(Response_list, MainActivity.this);
listView.setAdapter(adapter_view);
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
dialog.dismiss();
System.out.println("failed");
}
});
List<Table1> mList=new ArrayList();
ApiService api = RetroClient.getApiService();
Call<Example> call = api.getMyJson(38, 109);
call.enqueue(new Callback<Example>() {
#Override
public void onResponse(Call<Example> call, Response<Example> response) {
dialog.dismiss();
if (response.body.isSuccessful()) {
mList=response.body.getTable1();
adapter_view = new Adapter_view(mList,MainActivity.this);
listView.setAdapter(adapter_view);
}
}
#Override
public void onFailure(Call<Example> call, Throwable t) {
dialog.dismiss();
System.out.println("failed");
}
});

Android and Json

I have this project and wish to get all names from table like "1" is the first name how code this for all names
public void capturarPersonagens(View view) {
//-- Retrofit
callPersonagem = service.getPersonagem("1");
callPersonagem.enqueue(new Callback<Personagem>() {
#Override
public void onResponse(Call<Personagem> call, Response<Personagem> response) {
if (response.isSuccessful()) {
if (!call.isCanceled()) {
Log.i("Personagem",response.body().getName());
}
}
}
}
}
Best Regards
Pedro Duarte
You are missing a new method in your Service interface:
The api endpoint people/?format=json depends on the actual implementation of your webservice.
public interface Service {
#GET("people/{id}/?format=json")
Call<Personagem> getPersonagem(#Path("id") String alacazam);
#GET("people/?format=json")
Call<ArrayList<Personagem>> getPersonagens();
}
Then, you may consume it the same way you did with getPersonagem:
public void capturarPersonagens(View view) {
//-- Retrofit
callPersonagens = service.getPersonagens();
callPersonagens.enqueue(new Callback<ArrayList<Personagem>>() {
#Override
public void onResponse(Call<ArrayList<Personagem>> call, Response<ArrayList<Personagem>> response) {
if (response.isSuccessful()) {
if (!call.isCanceled()) {
for(Personagem p:response.body()){
Log.i("Personagem",p.getName());
}
}
}
}
#Override
public void onFailure(Call<ArrayList<Personagem>> call, Throwable t) {
Log.e("SW", "" + t.getMessage());
}
});
}

Categories

Resources