How to send list of objects on retrofit - android

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

Related

Post an array using retrofit 2

I need to post an array of attendees as shown in the image above. I tried using Hashmap but it gives some errors and I don't know if it is server-side error or retrofit.
Here is my code :
API interface
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#QueryMap Map<String,String> attendees,
#Field("token") String token);
Response class
String message;
public DefaultResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
And here is the code of my Activity
final Map<String,String> attendees = new HashMap<>();
for (int i = 0; i < attendeesTables.size(); i++){
attendees.put("id", String.valueOf(attendeesTables.get(i).getId()));
attendees.put("arrival_time",
attendeesTables.get(i).getArrival_time());
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendees,token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Am I doing everything in the right way?
I get request code 400(bad request)
You params are not correct that's why you getting 400 error. try like below
Request :
#FormUrlEncoded
#POST("vendor/event/{id}/checkin")
Call<DefaultResponse> updateAttendance(
#Path("id") int id,
#Field("attendees") String attendees,
#Field("token") String token);
Api Call :
JSONArray attendeesArray=new JSONArray();
for (int i = 0; i < attendeesTables.size(); i++){
JSONObject jsonObject=new JSONObject();
jsonObject.put("id",String.valueOf(attendeesTables.get(i).getId()));
jsonObject.put("arrival_time",String.valueOf(attendeesTables.get(i).getArrival_time()));
attendeesArray.put(jsonObject);
}
if (attendeesTables.size() > 0) {
Call<DefaultResponse> call = RetrofitClient.getmInstance().getApi().updateAttendance(event_id,attendeesArray.toString(),token);
call.enqueue(new Callback<DefaultResponse>() {
#Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
Toast.makeText(EventsDetailsActivity.this, response.code()+"", Toast.LENGTH_SHORT).show();
Toast.makeText(EventsDetailsActivity.this, response.isSuccessful()+"", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
Toast.makeText(EventsDetailsActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}

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

Handle JSON responce in retrofit 2.0

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

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

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