I am trying to making a POST request using retrofit2 but I am getting ErrorCode: 401. I am not finding the proper solution on the web that can help me out to solve my problem.
Data load for POST request
InsertAcitvity.java
private void insertData() {
String name = mName.getText().toString().trim();
String email = mEmail.getText().toString().trim();
String phone = mPhone.getText().toString().trim();
String full_address = mFull_address.getText().toString().trim();
String name_of_university = mName_of_university.getText().toString().trim();
int graduation_year = Integer.parseInt(mGraduation_year.getText().toString().trim());
double cgpa = Double.parseDouble(mCgpa.getText().toString().trim()) ;
String experience_in_months = mExperience_in_months.getText().toString().trim();
String current_work_place_name = mCurrent_work_place_name.getText().toString().trim();
String applying_in = mApplying_in.getText().toString().trim();
int expected_salary = Integer.parseInt(mExpected_salary.getText().toString().trim()) ;
String reference = mFeference.getText().toString().trim();
String github_project_url = mGithub_project_url.getText().toString().trim();
long creationTime= System.currentTimeMillis();
long updateTime= System.currentTimeMillis();
//String token = LoginActivity.token;
Intent intent = getIntent();
// declare token as member variable
String token = intent.getStringExtra("TOKEN_STRING");
String CvUniqueId = UUID.randomUUID().toString();
String tsync_id = UUID.randomUUID().toString();
cvFileObject = new CvFileObject(CvUniqueId);
mainObject = new MainObjectClass(tsync_id, name, email, phone, full_address, name_of_university, graduation_year, cgpa, experience_in_months,
current_work_place_name, applying_in, expected_salary,field_buzz_reference, github_project_url, cvFileObject, creationTime, updateTime);
ClientMethod clientMethod = ApiClient.getClient().create(ClientMethod.class);
Call<MainResponseObjectClass> call = clientMethod.getValue(token,mainObject);
call.enqueue(new Callback<MainResponseObjectClass>() {
#Override
public void onResponse(#NonNull Call<MainResponseObjectClass> call, #NonNull Response<MainResponseObjectClass> response) {
if (response.isSuccessful()){
Toast.makeText(InsertActivity.this, response.body().getTsync_id(), Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(InsertActivity.this, "access denied:(",Toast.LENGTH_LONG).show();
Log.d("ErrorCode", "onResponse: " + response.code());
}
}
#Override
public void onFailure(#NonNull Call<MainResponseObjectClass> call, #NonNull Throwable t) {
Log.d("Error", "onFailure: " + t.getMessage());
}
});
}
ClientMethod.java
public interface ClientMethod {
#POST("api/login/")
Call<Token>login(#Body Login login);
#POST("/api/v0/recruiting-entities/")
Call<MainResponseObjectClass> getValue(#Header("Authorization") String AutToken, #Body MainObjectClass mainObjectClass);
}
ApliClient.java
public class ApiClient {
public static final String BASE_URL = "https://myapi.test.com";
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit == null){
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
POST request code
CvFileObject.java
public class CvFileObject {
#SerializedName("tsync_id")
private String tsync_id;
public CvFileObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainObjectClass.java
public class MainObjectClass {
#SerializedName("tsync_id")
private String tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private int expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileObject fileObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
public MainObjectClass(String tsync_id, String name, String email, String phone, String full_address,
String name_of_university, int graduation_year, double cgpa, String experience_in_months,
String current_work_place_name, String applying_in, int expected_salary, String reference,
String github_project_url, CvFileObject fileObject, long on_spot_update_time, long on_spot_creation_time) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.fileObject = fileObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public int getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(int expected_salary) {
this.expected_salary = expected_salary;
}
public String reference() {
return reference;
}
public void setreference(String reference) {
this.reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileObject getFileObject() {
return fileObject;
}
public void setFileObject(CvFileObject fileObject) {
this.fileObject = fileObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
}
POST request response code
CvFileResponseObject.java
public class CvFileResponseObject {
#SerializedName("id")
int id;
#SerializedName("tsync_id")
private String tsync_id;
public CvFileResponseObject(String tsync_id) {
this.tsync_id = tsync_id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTsync_id() {
return tsync_id;
}
public void setTsync_id(String tsync_id) {
this.tsync_id = tsync_id;
}
}
MainResponseObjectClass.java
public class MainResponseObjectClass {
#SerializedName("tsync_id")
private int tsync_id;
#SerializedName("name")
private String name;
#SerializedName("email")
private String email;
#SerializedName("phone")
private String phone;
#SerializedName("full_address")
private String full_address;
#SerializedName("name_of_university")
private String name_of_university;
#SerializedName("graduation_year")
private int graduation_year;
#SerializedName("cgpa")
private double cgpa;
#SerializedName("experience_in_months")
private String experience_in_months;
#SerializedName("current_work_place_name")
private String current_work_place_name;
#SerializedName("applying_in")
private String applying_in;
#SerializedName("expected_salary")
private String expected_salary;
#SerializedName("reference")
private String reference;
#SerializedName("github_project_url")
private String github_project_url;
#SerializedName("cv_file")
private CvFileResponseObject cvFileResponseObject;
#SerializedName("on_spot_update_time")
long on_spot_update_time;
#SerializedName("on_spot_creation_time")
long on_spot_creation_time;
#SerializedName("success")
private boolean success;
#SerializedName("message")
private String message;
public MainResponseObjectClass(int tsync_id, String name, String email, String phone,
String full_address, String name_of_university, int graduation_year,
double cgpa, String experience_in_months, String current_work_place_name,
String applying_in, String expected_salary, String reference,
String github_project_url, CvFileResponseObject cvFileResponseObject, long on_spot_update_time,
long on_spot_creation_time, boolean success, String message) {
this.tsync_id = tsync_id;
this.name = name;
this.email = email;
this.phone = phone;
this.full_address = full_address;
this.name_of_university = name_of_university;
this.graduation_year = graduation_year;
this.cgpa = cgpa;
this.experience_in_months = experience_in_months;
this.current_work_place_name = current_work_place_name;
this.applying_in = applying_in;
this.expected_salary = expected_salary;
this.reference = reference;
this.github_project_url = github_project_url;
this.cvFileResponseObject = cvFileResponseObject;
this.on_spot_update_time = on_spot_update_time;
this.on_spot_creation_time = on_spot_creation_time;
this.success = success;
this.message = message;
}
public int getTsync_id() {
return tsync_id;
}
public void setTsync_id(int tsync_id) {
this.tsync_id = tsync_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFull_address() {
return full_address;
}
public void setFull_address(String full_address) {
this.full_address = full_address;
}
public String getName_of_university() {
return name_of_university;
}
public void setName_of_university(String name_of_university) {
this.name_of_university = name_of_university;
}
public int getGraduation_year() {
return graduation_year;
}
public void setGraduation_year(int graduation_year) {
this.graduation_year = graduation_year;
}
public double getCgpa() {
return cgpa;
}
public void setCgpa(double cgpa) {
this.cgpa = cgpa;
}
public String getExperience_in_months() {
return experience_in_months;
}
public void setExperience_in_months(String experience_in_months) {
this.experience_in_months = experience_in_months;
}
public String getCurrent_work_place_name() {
return current_work_place_name;
}
public void setCurrent_work_place_name(String current_work_place_name) {
this.current_work_place_name = current_work_place_name;
}
public String getApplying_in() {
return applying_in;
}
public void setApplying_in(String applying_in) {
this.applying_in = applying_in;
}
public String getExpected_salary() {
return expected_salary;
}
public void setExpected_salary(String expected_salary) {
this.expected_salary = expected_salary;
}
public String getField_buzz_reference() {
return field_buzz_reference;
}
public void setFeference(String reference) {
this.field_buzz_reference = reference;
}
public String getGithub_project_url() {
return github_project_url;
}
public void setGithub_project_url(String github_project_url) {
this.github_project_url = github_project_url;
}
public CvFileResponseObject getCvFileResponseObject() {
return cvFileResponseObject;
}
public void setCvFileResponseObject(CvFileResponseObject cvFileResponseObject) {
this.cvFileResponseObject = cvFileResponseObject;
}
public long getOn_spot_update_time() {
return on_spot_update_time;
}
public void setOn_spot_update_time(long on_spot_update_time) {
this.on_spot_update_time = on_spot_update_time;
}
public long getOn_spot_creation_time() {
return on_spot_creation_time;
}
public void setOn_spot_creation_time(long on_spot_creation_time) {
this.on_spot_creation_time = on_spot_creation_time;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Here I can see two APIs. But I am not sure which to which API you are getting 401. I can help you with the possibilities that you could check and please feel free to ask.
Assuming you are getting 401 for login API - the reason could be you are trying with wrong credentials.
Assuming you are getting 401 for getValue API - the reason could be you might passing the wrong token which you got from login response. Especially you need to cross-check the header with key and values.
And I have one suggestion - you could use header in Interceptor with retrofit setup itself.
Related
I have a payload string and want to change it to values of entity. The payload as below:
{"resultCode":"200","resultMessage":"Success","consent":[{"name":"A","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"1.0","updateDate":1600658621871},{"name":"B","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"2.0","updateDate":1874819158457},{"name":"C","sourceSystem":"IGN","updateBy":"Admin","remark":"good","version":"3.0","updateDate":1358819159457}]}
And the entities:
public class ListConsentResponse {
private String resultCode;
private String resultMessage;
private List<ConsentDTO> consent;
public String getResultCode() {
return resultCode;
}
public void setResultCode(String resultCode) {
this.resultCode = resultCode;
}
public String getResultMessage() {
return resultMessage;
}
public void setResultMessage(String resultMessage) {
this.resultMessage = resultMessage;
}
public List<ConsentDTO> getConsent() {
return consent;
}
public void setConsent(List<ConsentDTO> consent) {
this.consent = consent;
}
}
public class ConsentDTO {
private String name;
private String sourceSystem;
private String updateBy;
private String remark;
private String version;
private Timestamp updateDate;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceSystem() {
return sourceSystem;
}
public void setSourceSystem(String sourceSystem) {
this.sourceSystem = sourceSystem;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Timestamp getUpdateDate() {
return updateDate;
}
public void setUpdateDate(Timestamp updateDate) {
this.updateDate = updateDate;
}
}
But when I parse to json using GsonBuilder :
ListConsentResponse listConsentResponse = Utility.createGsonObject()
.fromJson(payload, ListConsentResponse.class);
I have error:
com.google.gson.JsonSyntaxException: 1600658621871
Is there any way help me get parse the string with Timestamp value to entity. Or at least can I change the Timestamp value to String value in payload (For example change 1600658621871 to "1600658621871").
Thanks.
I am trying to get the value of a JSON response and display it in my textView and editText. But I get a null object reference as an error.
JSON Response:
{
"srNo": 1,
"date": "11/14/2019 12:00:00 AM",
"fieldEngineer": "Angel",
"accountName": "Forever 21 Megamall",
"irNo": 1,
"joNo": 1,
"address": "Mandaluyong City",
"contactPerson": "Jansen Babon",
"designation": "",
"contactNo": "",
"email": "",
"timeIn": "00:00:00",
"timeOut": "00:00:00",
"productType": "Security",
"problem": ""
}
Java class:
private void fetchData() {
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, retrofit2.Response<ResObj> response) {
ResObj resObj = response.body();
String srNo = resObj.getSrNo();
String date = resObj.getDate();
String fieldEngineer = resObj.getFieldEngineer();
String accountName = resObj.getAccountName();
String irNo = resObj.getIrNo();
String joNo = resObj.getJoNo();
String address = resObj.getAddress();
String contactPerson = resObj.getContactPerson();
String designation = resObj.getDesignation();
String contactNo = resObj.getContactNo();
String email = resObj.getEmail();
String timeIn = resObj.getTimeIn();
String timeOut = resObj.getTimeOut();
String productType = resObj.getProductType();
String problem = resObj.getProblem();
//the response I am getting here is null
tvSrNo.setText(srNo);
etdate.setText(date);
etfieldengineer.setText(fieldEngineer);
etaccname.setText(accountName);
etirno.setText(irNo);
etjono.setText(joNo);
JsonObject workObj = new JsonObject();
try {
workObj.addProperty("srNo", resObj.getSrNo());
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
}
});
}
I tried using this tvSrNo.setText(resObj.getSrNo()) instead of tvSrNo.setText(srNo) but it still gets the same problem.
I am also using Retrofit.
I expect the result that JSON data will be placed in an editText or textView. But apparently, the response is getting null.
ResObj class:
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String message;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
public String getSrNo() {
return srNo;
}
public void setSrNo(String srNo) {
this.srNo = srNo;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getJoNo() {
return joNo;
}
public void setJoNo(String joNo) {
this.joNo = joNo;
}
public String getIrNo() {
return irNo;
}
public void setIrNo(String irNo) {
this.irNo = irNo;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
at com.example.android.ras.MainActivity$3.onResponse(MainActivity.java:187)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:71)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
Change your String to Integer
public class Codebeautify {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
// Getter Methods
public Integer getSrNo() {
return srNo;
}
public String getDate() {
return date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public Integer getIrNo() {
return irNo;
}
public Integer getJoNo() {
return joNo;
}
public String getAddress() {
return address;
}
public String getContactPerson() {
return contactPerson;
}
public String getDesignation() {
return designation;
}
public String getContactNo() {
return contactNo;
}
public String getEmail() {
return email;
}
public String getTimeIn() {
return timeIn;
}
public String getTimeOut() {
return timeOut;
}
public String getProductType() {
return productType;
}
public String getProblem() {
return problem;
}
// Setter Methods
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public void setDate(String date) {
this.date = date;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public void setAddress(String address) {
this.address = address;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public void setEmail(String email) {
this.email = email;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public void setProductType(String productType) {
this.productType = productType;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
Make your POJO class like this
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("srNo")
#Expose
private Integer srNo;
#SerializedName("date")
#Expose
private String date;
#SerializedName("fieldEngineer")
#Expose
private String fieldEngineer;
#SerializedName("accountName")
#Expose
private String accountName;
#SerializedName("irNo")
#Expose
private Integer irNo;
#SerializedName("joNo")
#Expose
private Integer joNo;
#SerializedName("address")
#Expose
private String address;
#SerializedName("contactPerson")
#Expose
private String contactPerson;
#SerializedName("designation")
#Expose
private String designation;
#SerializedName("contactNo")
#Expose
private String contactNo;
#SerializedName("email")
#Expose
private String email;
#SerializedName("timeIn")
#Expose
private String timeIn;
#SerializedName("timeOut")
#Expose
private String timeOut;
#SerializedName("productType")
#Expose
private String productType;
#SerializedName("problem")
#Expose
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
make sure to have Gson Converter in your retrofit instance
private static Retrofit getRetrofitInstance() {
return new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
then make call and put the data in ArrayList
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.android.ras.ResObj.getSrNo()' on a null object reference
Note: NullPointerException because you did not declare SrNo inside the model class
Try to use a jason to java class generator:
http://www.jsonschema2pojo.org/
Source type: JSON
Annotation style: Gson( if you used GSON) or none
Include getters and setters
public class Example {
private Integer srNo;
private String date;
private String fieldEngineer;
private String accountName;
private Integer irNo;
private Integer joNo;
private String address;
private String contactPerson;
private String designation;
private String contactNo;
private String email;
private String timeIn;
private String timeOut;
private String productType;
private String problem;
public Integer getSrNo() {
return srNo;
}
public void setSrNo(Integer srNo) {
this.srNo = srNo;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getFieldEngineer() {
return fieldEngineer;
}
public void setFieldEngineer(String fieldEngineer) {
this.fieldEngineer = fieldEngineer;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Integer getIrNo() {
return irNo;
}
public void setIrNo(Integer irNo) {
this.irNo = irNo;
}
public Integer getJoNo() {
return joNo;
}
public void setJoNo(Integer joNo) {
this.joNo = joNo;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContactPerson() {
return contactPerson;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimeIn() {
return timeIn;
}
public void setTimeIn(String timeIn) {
this.timeIn = timeIn;
}
public String getTimeOut() {
return timeOut;
}
public void setTimeOut(String timeOut) {
this.timeOut = timeOut;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getProblem() {
return problem;
}
public void setProblem(String problem) {
this.problem = problem;
}
}
first : Check response output,
you can Log.i or Toast it,,,
If your response not load or null ... - (the Problem in here)
Second : if respon Ok, Check your ResObj.getSrNo().
Print again... check
String srNo = resObj.getSrNo();
Log.i srNo... (problem or not)
Or checkyour Class Codebeautify
JsonObject paramObject = new JsonObject();
Call<ResObj> call = userService.userLogin(paramObject); // paramObject is empty object
You are passing empty JsonObject to your API parameter.
So you have to add parameter value to your paramObject. like this
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
// add other properties if you have
} catch (JSONException e) {
e.printStackTrace();
}
after that you should call your api like
Call<ResObj> call = userService.userLogin(paramObject);
As i am seeing the problem is in parsing, The retrofit can not mapping as your response is n't having ResObj as root.
{ "ResObj": { "srNo": 1, "date": "11/14/201912: 00: 00AM", "fieldEngineer": "Angel", "accountName": "Forever21Megamall", "irNo": 1, "joNo": 1, "address": "MandaluyongCity", "contactPerson": "JansenBabon", "designation": "", "contactNo": "", "email": "", "timeIn": "00: 00: 00", "timeOut": "00: 00: 00", "productType": "Security", "problem": "" } }
Modify your response or change your request
Call<JSONObject> call = userService.userLogin(paramObject);
Later in extract the values manually.
call.enqueue(new Callback<Resul>() {
#Override
public void onResponse(Call<Resul> call, Response<Resul> response) {
progressDialog.dismiss();
Log.d("response", "code = " + response.code());
Log.d("mvvvv","StudentId : "+response.body().toString());
String h=response.body().toString();
if("1".equals(h)){
Intent i = new Intent(Login.this,MainActivity.class);
startActivity(i);
}
else {
Toast.makeText(getApplicationContext()," user name not valid " , Toast.LENGTH_LONG).show();
}
}
Pojo class
package com.example.admin.myappl.Interface;
public class Resul {
private User_info user_info;
private Response Response;
public User_info getUser_info ()
{
return user_info;
}
public void setUser_info (User_info user_info)
{
this.user_info = user_info;
}
public Response getResponse ()
{
return Response;
}
public void setResponse (Response Response)
{
this.Response = Response;
}
public String toString() {
return ""+Response+"";
}
public class Response
{
private String response_message;
private String response_code;
public String getResponse_message ()
{
return response_message;
}
public void setResponse_message (String response_message)
{
this.response_message = response_message;
}
public String getResponse_code ()
{
return response_code;
}
public void setResponse_code (String response_code)
{
this.response_code = response_code;
}
#Override
public String toString()
{
return response_code;
}
}
public class User_info
{
private String profile_picture;
private String lastweek_command;
private String weight;
private String student_id;
private String push_notification_status;
private String id;
private String first_name;
private String updated_at;
private String height;
private String blood_group;
private String email;
private String address;
private String dob;
private String last_name;
private String gender;
private String general_command;
private String activity;
private String mobile_no;
public String getProfile_picture ()
{
return profile_picture;
}
public void setProfile_picture (String profile_picture)
{
this.profile_picture = profile_picture;
}
public String getLastweek_command ()
{
return lastweek_command;
}
public void setLastweek_command (String lastweek_command)
{
this.lastweek_command = lastweek_command;
}
public String getWeight ()
{
return weight;
}
public void setWeight (String weight)
{
this.weight = weight;
}
public String getStudent_id ()
{
return student_id;
}
public void setStudent_id (String student_id)
{
this.student_id = student_id;
}
public String getPush_notification_status ()
{
return push_notification_status;
}
public void setPush_notification_status (String push_notification_status)
{
this.push_notification_status = push_notification_status;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getFirst_name ()
{
return first_name;
}
public void setFirst_name (String first_name)
{
this.first_name = first_name;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String getHeight ()
{
return height;
}
public void setHeight (String height)
{
this.height = height;
}
public String getBlood_group ()
{
return blood_group;
}
public void setBlood_group (String blood_group)
{
this.blood_group = blood_group;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getDob ()
{
return dob;
}
public void setDob (String dob)
{
this.dob = dob;
}
public String getLast_name ()
{
return last_name;
}
public void setLast_name (String last_name)
{
this.last_name = last_name;
}
public String getGender ()
{
return gender;
}
public void setGender (String gender)
{
this.gender = gender;
}
public String getGeneral_command ()
{
return general_command;
}
public void setGeneral_command (String general_command)
{
this.general_command = general_command;
}
public String getActivity ()
{
return activity;
}
public void setActivity (String activity)
{
this.activity = activity;
}
public String getMobile_no ()
{
return mobile_no;
}
public void setMobile_no (String mobile_no)
{
this.mobile_no = mobile_no;
}
#Override
public String toString()
{
return "ClassPojo [profile_picture = "+profile_picture+", lastweek_command = "+lastweek_command+", weight = "+weight+", student_id = "+student_id+", push_notification_status = "+push_notification_status+", id = "+id+", first_name = "+first_name+", updated_at = "+updated_at+", height = "+height+", blood_group = "+blood_group+", email = "+email+", address = "+address+", dob = "+dob+", last_name = "+last_name+", gender = "+gender+", general_command = "+general_command+", activity = "+activity+", mobile_no = "+mobile_no+"]";
}
}
}
Instead of
String h=response.body().toString();
Use
Resul result = response.body();
If condition should be like this
if("1".equals(result.getResponse().getResponse_code())
Use http://www.jsonschema2pojo.org/ to generate pojo class
If you are using gson for parsing the #SerializedName("your_key") ,
#Expose these 2 tags are required. Otherwise those values will be null
This question already has an answer here:
How to convert JSONArray to List with Gson?
(1 answer)
Closed 6 years ago.
How to convert a jsonArray with multiple jsonObjects to an arraylist using Gson.
Here is my Json String:
[{"AccommoAddress":{
"PostalCode":2109,
"Street":"22 Ararat Str",
"Town":"Westdene"
},
"AccommoDetails":{
"AccommoId":0,
"CleaningService":1,
"DSTV":1,
"DedicatedStudyArea":1
},
"AccommoID":1,
"AccommoMainImage":{
"CategoryId":0,
"ContentType":".png",
"DateUploaded":"2016-07-16",
"FileSize":2362,
"ImageCategory":"MAIN",
"ImageId":1,
"ImageName":"images.png"
}]
First , it's not a correct Json format.
"ImageName":"images.png" <- (you need to put a "}" here )
Second , create a entity
public class TargetEntity {
private AccommoAddressEntity AccommoAddress;
private AccommoDetailsEntity AccommoDetails;
private int AccommoID;
private AccommoMainImageEntity AccommoMainImage;
public AccommoAddressEntity getAccommoAddress() {
return AccommoAddress;
}
public void setAccommoAddress(AccommoAddressEntity AccommoAddress) {
this.AccommoAddress = AccommoAddress;
}
public AccommoDetailsEntity getAccommoDetails() {
return AccommoDetails;
}
public void setAccommoDetails(AccommoDetailsEntity AccommoDetails) {
this.AccommoDetails = AccommoDetails;
}
public int getAccommoID() {
return AccommoID;
}
public void setAccommoID(int AccommoID) {
this.AccommoID = AccommoID;
}
public AccommoMainImageEntity getAccommoMainImage() {
return AccommoMainImage;
}
public void setAccommoMainImage(AccommoMainImageEntity AccommoMainImage) {
this.AccommoMainImage = AccommoMainImage;
}
public static class AccommoAddressEntity {
private int PostalCode;
private String Street;
private String Town;
public int getPostalCode() {
return PostalCode;
}
public void setPostalCode(int PostalCode) {
this.PostalCode = PostalCode;
}
public String getStreet() {
return Street;
}
public void setStreet(String Street) {
this.Street = Street;
}
public String getTown() {
return Town;
}
public void setTown(String Town) {
this.Town = Town;
}
}
public static class AccommoDetailsEntity {
private int AccommoId;
private int CleaningService;
private int DSTV;
private int DedicatedStudyArea;
public int getAccommoId() {
return AccommoId;
}
public void setAccommoId(int AccommoId) {
this.AccommoId = AccommoId;
}
public int getCleaningService() {
return CleaningService;
}
public void setCleaningService(int CleaningService) {
this.CleaningService = CleaningService;
}
public int getDSTV() {
return DSTV;
}
public void setDSTV(int DSTV) {
this.DSTV = DSTV;
}
public int getDedicatedStudyArea() {
return DedicatedStudyArea;
}
public void setDedicatedStudyArea(int DedicatedStudyArea) {
this.DedicatedStudyArea = DedicatedStudyArea;
}
}
public static class AccommoMainImageEntity {
private int CategoryId;
private String ContentType;
private String DateUploaded;
private int FileSize;
private String ImageCategory;
private int ImageId;
private String ImageName;
public int getCategoryId() {
return CategoryId;
}
public void setCategoryId(int CategoryId) {
this.CategoryId = CategoryId;
}
public String getContentType() {
return ContentType;
}
public void setContentType(String ContentType) {
this.ContentType = ContentType;
}
public String getDateUploaded() {
return DateUploaded;
}
public void setDateUploaded(String DateUploaded) {
this.DateUploaded = DateUploaded;
}
public int getFileSize() {
return FileSize;
}
public void setFileSize(int FileSize) {
this.FileSize = FileSize;
}
public String getImageCategory() {
return ImageCategory;
}
public void setImageCategory(String ImageCategory) {
this.ImageCategory = ImageCategory;
}
public int getImageId() {
return ImageId;
}
public void setImageId(int ImageId) {
this.ImageId = ImageId;
}
public String getImageName() {
return ImageName;
}
public void setImageName(String ImageName) {
this.ImageName = ImageName;
}
}
}
Third
Gson gson = new Gson();
TargetEntity[] target = gson.fromJson(JsonString,TargetEntity[].class)
I have two classes which implement Parcelable. And objects of one of them I have to write to a list. First model:
public class Challenge implements Parcelable {
private long id;
#JsonProperty("max_volume")
private int maxVolume;
#JsonProperty("current_volume")
private int currentVolume;
private String name;
private String description;
#JsonProperty("max_count")
private int maxCount;
#JsonProperty("date_from")
private Date dateFrom;
#JsonProperty("date_to")
private Date dateTo;
#JsonProperty("create_time")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
private Date createTime;
private ChallengeStatus status;
#JsonProperty("update_date")
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
private Date updateTime;
private ChallengeCategory category;
private Subject subject;
private ArrayList<User> userArrayList;
private int practice;
public double getProgress() {
return progress;
}
public void setProgress(double progress) {
this.progress = progress;
}
public int getPractice() {
return practice;
}
public void setPractice(int practice) {
this.practice = practice;
}
private double progress;
public Challenge() {
}
private Creator<User> creator;
protected Challenge(Parcel in) {
id = in.readLong();
maxVolume = in.readInt();
currentVolume = in.readInt();
name = in.readString();
description = in.readString();
maxCount = in.readInt();
// dateFrom = new Date(in.readLong());
// dateTo = new Date(in.readLong());
// createTime = new Date(in.readLong());
// status = ChallengeStatus.getEnum(in.readString());
// updateTime = new Date(in.readLong());
// category = ChallengeCategory.getEnum(in.readString());
subject = in.readParcelable(Subject.class.getClassLoader());
userArrayList = in.readTypedList(userArrayList, User.CREATOR);
}
public static final Creator<Challenge> CREATOR = new Creator<Challenge>() {
#Override
public Challenge createFromParcel(Parcel in) {
return new Challenge(in);
}
#Override
public Challenge[] newArray(int size) {
return new Challenge[size];
}
};
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getMaxVolume() {
return maxVolume;
}
public void setMaxVolume(int maxVolume) {
this.maxVolume = maxVolume;
}
public int getCurrentVolume() {
return currentVolume;
}
public void setCurrentVolume(int currentVolume) {
this.currentVolume = currentVolume;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getMaxCount() {
return maxCount;
}
public void setMaxCount(int maxCount) {
this.maxCount = maxCount;
}
public Date getDateFrom() {
return dateFrom;
}
public void setDateFrom(Date dateFrom) {
this.dateFrom = dateFrom;
}
public Date getDateTo() {
return dateTo;
}
public void setDateTo(Date dateTo) {
this.dateTo = dateTo;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public ChallengeStatus getStatus() {
return status;
}
public void setStatus(ChallengeStatus status) {
this.status = status;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public ChallengeCategory getCategory() {
return category;
}
public void setCategory(ChallengeCategory category) {
this.category = category;
}
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
#Override
public int describeContents() {
return 0;
}
public ArrayList<User> getUserArrayList() {
return userArrayList;
}
public void setUserArrayList(ArrayList<User> userArrayList) {
this.userArrayList = userArrayList;
}
public static Creator<Challenge> getCREATOR() {
return CREATOR;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeInt(maxVolume);
dest.writeInt(currentVolume);
dest.writeString(name);
dest.writeString(description);
dest.writeInt(maxCount);
// dest.writeLong(dateFrom.getTime());
// dest.writeLong(dateTo.getTime());
// dest.writeLong(createTime.getTime());
// dest.writeString(status.toString());
// dest.writeLong(updateTime.getTime());
// dest.writeString(category.toString());
dest.writeParcelable(subject, flags);
dest.writeTypedList(userArrayList);
}
}
And I have a problem at this line: userArrayList = in.readTypedList(userArrayList, User.CREATOR); It looks like this: And example of the second model:
public class User implements Parcelable {
long id;
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm ZZZZ")
Date time;
String image_src;
String first_name;
String last_name;
public User() {
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getImage_src() {
return image_src;
}
public void setImage_src(String image_src) {
this.image_src = image_src;
}
protected User(Parcel parcel) {
id = parcel.readLong();
time = new Date(parcel.readLong());
image_src = parcel.readString();
first_name = parcel.readString();
last_name = parcel.readString();
}
public static final Creator<User> CREATOR = new Creator<User>() {
#Override
public User createFromParcel(Parcel in) {
return new User(in);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
public static Creator<User> getCREATOR() {
return CREATOR;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(id);
// parcel.writeLong(time.getTime());
parcel.writeString(image_src);
parcel.writeString(first_name);
parcel.writeString(last_name);
}
}
Can you help me to find my mistake?
You must initialized userArrayList before use it:
userArrayList = new ArrayList<User>();
in.readTypedList(userArrayList, User.CREATOR);
Initialize ArraList and retrieve the data to this list from parcelable.
Something like this:
userArrayList = new ArrayList<User>();
in.readTypedList(userArrayList, User.CREATOR);