Handle JSON responce in retrofit 2.0 - android

I know this is old or repeat question. But I didn't get where am I wrong.
I got result null from this JSON.
{
"error": {
"dateTimeUtc": "2017-12-26T05:46:05.1126801+00:00",
"errorReference": "sample string 2",
"errorType": "Error",
"title": "sample string 3",
"code": "sample string 4",
"messages": [
"sample string 1",
"sample string 2"
]
},
"result": {
"message": "sample string 1"
}
}
I have this type of JSON to read from Retrofit2.
I create one POJO class called RetrofitResponce
private Error error;
private Result result;
public Result getResult ()
{
return result;
}
public void setResult (Result result)
{
this.result = result;
}
public Error getError ()
{
return error;
}
public void setError (Error error)
{
this.error = error;
}
#Override
public String toString()
{
return "ClassPojo [result = "+result+", error = "+error+"]";
}`
Now in call.enque() method to handled response, like
call.enqueue(new Callback<RegisterUser>() {
#Override
public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {
try {
RetrofitResponce retrofitResponce= response.body();
Error error = retrofitResponce.getError();
Result result=retrofitResponce.getResult();
Log.e("Eroor", "rr " + error.getTitle().toString());
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<RetrofitResponce> call, Throwable t) {
Log.e("Failure ", "fail " + t.toString());
}
});
but here I get NullPointerException,i.e. I don't get any response in RestrofitResponce. Error and Result both get Null.
java.lang.NullPointerException: Attempt to invoke virtual method 'net.xyz.abc.Model.Error net.xyz.abc.Model.RegisterUser.getError()' on a null object reference
Please help me. try to solve my query.Thanks in advance.
PostMan responce,
{
"error": {
"dateTimeUtc": "2017-12-26T07:05:51.1427712Z",
"errorReference": "00000000-0000-0000-0000-000000000000",
"errorType": "Error",
"title": "The request is invalid.",
"code": null,
"messages": [
"Passwords must have at least one non letter or digit character. Passwords must have at least one uppercase ('A'-'Z')."
]
},
"result": null
}

Retrofit callback needs response model, just change this:
call.enqueue(new Callback<RetrofitResponce>() {
#Override
public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {
if (response.isSuccessful()) {
RetrofitResponce retrofitResponce= response.body();
if (retrofitResponce!=null) {
Error error = retrofitResponce.getError();
Result result=retrofitResponce.getResult();
Log.e("Eroor", "rr " + error.getTitle().toString());
}
}
}
#Override
public void onFailure(Call<RetrofitResponce> call, Throwable t) {
Log.e("Failure ", "fail " + t.toString());
}
});
Happy coding!!

You have to add the #SerializedName in your Response class for each and every filed same as the web service name.
e.g
#SerializedName("error")
private Error error;
#SerializedName("result")
private Result result;
Please use this website to create your classes from the JSON Response.
http://www.jsonschema2pojo.org/
And after that you have to check if response if successful or not.
call.enqueue(new Callback<RegisterUser>() {
#Override
public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {
try
{
if(response.isSuccessful() && response.body() != null)
{
RetrofitResponce retrofitResponce= response.body();
Error error = retrofitResponce.getError();
Result result=retrofitResponce.getResult();
}
} catch (Exception e) {
}
}
#Override
public void onFailure(Call<RetrofitResponce> call, Throwable t) {
Log.e("Failure ", "fail " + t.toString());
}
});

Try this Pojo for RetrofitResponce
public class RetrofitResponce {
#SerializedName("error")
#Expose
private Error error;
#SerializedName("result")
#Expose
private Result result;
public Error getError() {
return error;
}
public void setError(Error error) {
this.error = error;
}
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
public class Result {
#SerializedName("message")
#Expose
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public class Error {
#SerializedName("dateTimeUtc")
#Expose
private String dateTimeUtc;
#SerializedName("errorReference")
#Expose
private String errorReference;
#SerializedName("errorType")
#Expose
private String errorType;
#SerializedName("title")
#Expose
private String title;
#SerializedName("code")
#Expose
private String code;
#SerializedName("messages")
#Expose
private List<String> messages = null;
public String getDateTimeUtc() {
return dateTimeUtc;
}
public void setDateTimeUtc(String dateTimeUtc) {
this.dateTimeUtc = dateTimeUtc;
}
public String getErrorReference() {
return errorReference;
}
public void setErrorReference(String errorReference) {
this.errorReference = errorReference;
}
public String getErrorType() {
return errorType;
}
public void setErrorType(String errorType) {
this.errorType = errorType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<String> getMessages() {
return messages;
}
public void setMessages(List<String> messages) {
this.messages = messages;
}
}

Try this.
call.enqueue(new Callback<RetrofitResponce>() {
#Override
public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {
if (response.body() != null)
Toast.makeText(YourActivity.this,response.body().getResult(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<RetrofitResponce> call, Throwable t) {
Log.e("Failure ", "fail " + t.toString());
}
});

I am sure this will help you.
You can not handle Success and Faille by Single model.
To get error body you need to call response.errorBody().string()
Try Below Code :
call.enqueue(new Callback<RegisterUser>() {
#Override
public void onResponse(Call<RetrofitResponce> call, Response<RetrofitResponce> response) {
try {
if (response.isSuccessful()) {
Log.d("Successful",response.body(););
} else {
Log.d("errorBody ", response.errorBody().string());
}
} catch (Exception e) {
Log.d("Exception ",e.toString());
}
}
#Override
public void onFailure(Call<RetrofitResponce> call, Throwable t) {
Log.e("Failure ", "fail " + t.toString());
}
});

Related

How to send list of objects on retrofit

I need to send list of below objects on retrofit , but always I receive error , your body is null
{
"height": "20",
"weight": "40",
"unit": "kg"
}
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<ResponseBody> call = service.getAllPhotos("");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.v("SUCCESS", response.body() + " ");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
First you have to create your models use click here
Your model will be like this
public class User {
#SerializedName("height")
#Expose
private String height;
#SerializedName("weight")
#Expose
private String weight;
#SerializedName("unit")
#Expose
private String unit;
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getUnit() {
return unit;
}
public void setUnit(String unit) {
this.unit = unit;
}
}
On your API interface create this method
#POST("/service name for example register")
Call<ResponseBody> postUsers(#Body List<User> userRequest);
On Main Activity use below code
public void postUsers(List<Users> userRequest) {
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<ResponseBody> call = service.postUsers(userRequest);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.v("SUCCESS", response.body() + " ");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}

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.

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

Read Response body in retrofit2

I am accessing webservice API using retrofit2. The response from API is in JSON Format.
JSONResponseImage
In retrofit my client is making successful connection with API but I want to access "statusMessage": "Email Address already exists" which is sent by webservice. I have tried couple of things but no success.
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
} else {
switch(response.code()) {
case 409:
Log.e("TAG", "1: " +response.raw());
Toast.makeText(MainActivity.this, "email already Registered",
Toast.LENGTH_SHORT).show();
break;
}
}
}
seeImageLog
Add the following to your User class
private Integer statusCode;
private String statusMessage;
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public String getStatusMessage() {
return statusMessage;
}
public void setStatusMessage(String statusMessage) {
this.statusMessage = statusMessage;
}
Now you can access getStatusMessage() like response.body().getStatusMessage();
NOTE : setters are not necessary, adding getters will do the job
Use this code:
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
//This is the status message.
String statusMessage = response.body().getStatusMessage();
} else {
switch(response.code()){
case 409:
Log.e("TAG", "1: " +response.raw());
Toast.makeText(MainActivity.this, "email already Registered", Toast.LENGTH_SHORT).show();
break;
}
}
}
The User class:
public class User {
//No need to declare setStatusMessage as the value shall be set by retrofit automatically. No need to make this as public.
private String statusMessage;
public String getStatusMessage() {
//Return statusMessage declared in User class.
return statusMessage;
}
}

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