how to make generic retrofit library for api calling - android

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

Related

How to read the String response from Retrofit

I need to handle a functionality based on the retrofit response.
The post method has the request as json format and getting the response as Text true
I have tried to get this response as the following code snippet. But always I get false though I get true in postman response.
private void callPostLoginAPI(String webServiceResponse) {
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> result = apiService.getPostDealer(postLoginAPI(webServiceResponse));
result.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String postLoginResponse = null;
try {
postLoginResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
if (postLoginResponse != null || (!postLoginResponse.equals(""))) {
if (postLoginResponse.equals("true")) {
try {
if (PreferenceClass.getInstallationID(Loginpage.this) == null ||
PreferenceClass.getInstallationID(Loginpage.this).equals("")) {
request_appInstallation_API(0);
} else {
checkAppUpdate();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(Loginpage.this, "Please contact CMS Admin", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(Loginpage.this, "Something went wrong... Please try again", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(Loginpage.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
UPDATE:
As I tried the following,and I havent gotten the respective "Postman response value" .
ApiInterface apiService = ApiClient.getClient1().create(ApiInterface.class);
Call<Boolean> result = apiService.getPostDealer(postLoginAPI(webServiceResponse));
result.enqueue(new Callback<Boolean>() {
#Override
public void onResponse(Call<Boolean> call, Response<Boolean> response) {
Log.i("Response", response.body().toString());
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("callPostLoginAPI", response.body().toString());
Toast.makeText(Dealer_Loginpage.this, "returned", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(Dealer_Loginpage.this, "Nothing returned", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onFailure(Call<Boolean> call, Throwable t) {
Toast.makeText(Dealer_Loginpage.this, "Nothing returned", Toast.LENGTH_LONG).show();
}
});
ApiClient.getClient1() :
public static Retrofit getClient1() {
if (retrofit1 == null) {
retrofit1 = new Retrofit.Builder().baseUrl(GlobalClass.sBase_Url).
addConverterFactory(ScalarsConverterFactory.create()).
addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit1;
}
Solution:
Attach this:
postLoginResponse.replaceAll("[^A-Za-z]+", "");
After the line:
postLoginResponse = response.body().string();
and try.

Jwt token refresh?

I have an API for refreshing a token, but I am not able to use refresh token in my app, after a user login a token gets expired after 60min so now I want to refresh the user token, how can I use refresh token in my app
my interface of refresh token:
#POST("/api/token/refresh")
Call<ResponseBody> getAccessToken();
My Session:
public class Session {
Context context;
private SharedPreferences prefs;
private Session session;
public Session(Context cntx) {
// TODO Auto-generated constructor stub
this.context = cntx;
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public void setJwtToken(String token) {
prefs.edit().putString("token", token).commit();
}
public String getJwtToken() {
String token = prefs.getString("token", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
}
return token;
}
public String getRefreshToken() {
String token = prefs.getString("RefreshToken", "");
if (token == null || token.isEmpty()) {
token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjIxNzc0NTI3OTksImlhdCI6MTUxNjAyMjk5OSwiaXNzIjoiQmFzb2JhYXMgTmVwYWwiLCJuYmYiOjE1MTYwMjI5OTksImp0aSI6Ikd1ZXN0VG9rZW4iLCJzdWIiOjB9.QikmNgBYmqch5HREGFEpUs4Xk3x-zFfDg5mhYJO7jM8";
ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.getAccessToken();
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
JSONObject resultObject = new JSONObject();
JSONObject tokenObject = null;
try {
tokenObject = resultObject.getJSONObject("token");
} catch (JSONException e) {
e.printStackTrace();
}
String newToken = null;
try {
newToken = tokenObject.getString("accessToken");
} catch (JSONException e) {
e.printStackTrace();
}
newToken = "Bearer " + newToken;
session.setJwtToken(newToken);
Log.e("Token Result Object", session.getJwtToken());
Log.e("Token Response Object", session.getRefreshToken());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
return token;
}
public void setRefreshToken(String token) {
prefs.edit().putString("RefreshToken", token).commit();
}
My login:
public class LoginActivity extends AppCompatActivity {
private Button userLogin;
ApiInterface apiInterface;
private EditText loginEmail, loginPassword;
private User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginEmail = findViewById(R.id.loginEmail);
loginPassword = findViewById(R.id.loginPassword);
userLogin = findViewById(R.id.loginButton);
userLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
TextView register = (TextView) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), SignUpActivity.class);
startActivity(intent);
}
});
ImageView back = (ImageView) findViewById(R.id.back_arrow_login);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
public void userLogin() {
final User user = new User();
final Session session = new Session(this);
user.setEmail(loginEmail.getText().toString().trim());
user.setPassword(loginPassword.getText().toString().trim());
apiInterface = ApiClient.getClient().create(ApiInterface.class);
Call<ResponseBody> call = apiInterface.logMeIn(session.getJwtToken(),user);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.code() == 200) {
try {
JSONObject jsonObject = new JSONObject(response.body().string());
JSONObject dataObject = jsonObject.getJSONObject("data");
String token = dataObject.getString("access_token");
String refToken = dataObject.getString("refresh_token");
session.setJwtToken("Bearer " + token);
session.setRefreshToken("Bearer"+refToken);
String name=user.getName();
Toast.makeText(LoginActivity.this, "WELCOME", Toast.LENGTH_SHORT).show();
Log.e("USER", jsonObject.toString());
startActivity(new Intent(LoginActivity.this, MainActivity.class));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} else
Log.e("TestActivity", response.raw().toString());
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
}
}
Please help me clear out the method or process ,so that i can refresh the user token after it gets expired
public class ServiceFactory {
private static final long CONNECTION_TIMEOUT = 60 * 1000; // one minute
private Activity activity;
public ServiceFactory(Activity activity) {
this.activity = activity;
}
public static <T> T createService(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
public <T> T createServiceWithToken(final Class<T> clazz) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(getHttpClientBuilder())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(clazz);
}
private OkHttpClient getHttpClientBuilder() {
// Setup OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.readTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS)
.authenticator(new TokenAuthenticator());
return builder.build();
}
private void logout() {
if (activity != null) {
Intent intent = new Intent(activity, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
activity.finish();
}
}
class TokenAuthenticator implements Authenticator {
#Nullable
#Override
public Request authenticate(#NonNull Route route, #NonNull Response response) throws IOException {
TokenManager tokenManager = new TokenManager();
//called renew api call
retrofit2.Response<ResponseModel> responseModel= ServiceFactory.createService(YOUR_API.class)
.renewToken(tokenManager.getBearer())
.execute();
if (responseModel.code() == 401) {
//remove token
logout();
return null;
} else {
//saved token to local
}
//returned new reuwst with updated header
return response.request().newBuilder()
.header(APIConstants.AUTHORIZATION, tokenManager.getBearer())
.build();
}
}
}

Login with retrofit third party lib

http://localhost/shop/api2/login.php?email=xxxx#gmail.com&password=xxxxx
{"success":1,"customer_id":"2","customer_group_id":"0","email":"tanaji#gmail.com"}
private void attemptLogin(final String email, final String password) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("http://192.168.1.14/shop/api2/")
.build();
LoginApi service = retrofit.create(LoginApi.class);
User user = new User();
user.setEmail(email);
user.setPassword(password);
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
ResponseBody resp = response.body();
if (resp != null && resp.equals(1)) {
Toast.makeText(MainActivity.this, "Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
});
if (response.isSuccessful() && response.body() != null && response.body().getStatus().equalsIgnoreCase("success")) {
.getStatus is not working in my code.
and if success: 1 then its want login and then open to new page.
how to get json resopnse successfully?
Make ResponseBody Model
public class ResponseBody
{
private String customer_group_id;
private String email;
private String success;
private String customer_id;
public String getCustomer_group_id ()
{
return customer_group_id;
}
public void setCustomer_group_id (String customer_group_id)
{
this.customer_group_id = customer_group_id;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getSuccess ()
{
return success;
}
public void setSuccess (String success)
{
this.success = success;
}
public String getCustomer_id ()
{
return customer_id;
}
public void setCustomer_id (String customer_id)
{
this.customer_id = customer_id;
}
#Override
public String toString()
{
return "ClassPojo [customer_group_id = "+customer_group_id+", email =
"+email+", success = "+success+", customer_id = "+customer_id+"]";
}
}
Call Retrofit
Call<ResponseBody> userCall = service.login(email,password);
userCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.body()!=null)
if(response.body().
getSuccess().contains("1"){
Toast.makeText(MainActivity.this,
"Response"+response.body(), Toast.LENGTH_SHORT).show();
Intent in = new Intent(MainActivity.this,
ProfileActivity.class);
startActivity(in);
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
});

Login Activity in Retrofit library in android

this is my login api i want to login the app.
private void attemptLogin(final String email,final String password) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BaseUrl)
.build();
LoginApi service = retrofit.create(LoginApi.class);
final User user = new User();
user.setEmail(email);
user.setPassword(password);
final Call<List<User>> userCall = service.login(email,password);
userCall.enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
Toast.makeText(MainActivity.this, " Fail to login ", Toast.LENGTH_SHORT).show();
}
});
}
}
http://192.168.1.14/shop/api2/login.php?email=xxxxxx#gmail.com&password=xxxxxx
Add these lines in build.gradle file:
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
Create a public interface for your api params:
eg. #POST("api/auth")
Call<Auth> auth(#Field("username") String username, #Field("password") String password);
private void executeAuthEndpoint() {
String _loginId = loginId.getText().toString();
String _password = password.getText().toString();
if (_loginId.length() > 0 && _password.length() > 0) {
endpoint.auth(_loginId, _password).enqueue(new Callback<Auth>() {
#Override
public void onResponse(Call<Auth> call, Response<Auth> response) {
if (response.isSuccessful() && response.body() != null && response.body().getStatus().equalsIgnoreCase("success")) {
// your code
}
else if (response.body()!=null && response.body().getMessage()!=null) {
Toast.makeText(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), R.string.message_auth_fail, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<Auth> call, Throwable t) {
if (call.isExecuted()) return;
ErrorHandler.handleError(getActivity(), t);
}
});
} else {
Toast.makeText(getActivity(), R.string.message_empty_field, Toast.LENGTH_SHORT).show();
}
}

How to get Json response in retrofit version 2.0.2?

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

Categories

Resources