Error in Code for Get & Post Request in Retrofit 2 - java

I have an Api, Api = "http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/admin/"
I am new to Retrofit2, If some one can help me through my code
I have an Error while doing GET and POST Request
While Using Get Api: the Username and password are null
While Using Post Api: I am getting 404 Error code
Login Activity:
private JsonPlaceHolderApi jsonPlaceHolderApi;
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);
getLogin();
createPost();
}
private void getLogin()
{
Call<Login> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<Login>()
{
#Override
public void onResponse(Call<Login> call, Response<Login> response)
{
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login logins = response.body();
String content = "";
content += "UserName: " + logins.getUsername() + "\n";
content += "Password: " + logins.getPassword() + "\n";
content += "Status: " + logins.getStatus() + "\n";
content += "Description: " + logins.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<Login> call, Throwable t)
{
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
Login login = new Login("New Name", "New Password");
Call<Login> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<Login>() {
#Override
public void onResponse(Call<Login> call, Response<Login> response) {
if (!response.isSuccessful())
{
Log.i("Code: " , String.valueOf(response.code()));
return;
}
Login loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.getUsername() + "\n";
content += "Password: " + loginResponse.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me",content);
}
#Override
public void onFailure(Call<Login> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
Login Class:
String username;
String password;
int Status;
String Description;
public Login(String username, String password)
{
this.username = username;
this.password = password;
}
public String getUsername()
{
return username;
}
public String getPassword()
{
return password;
}
public int getStatus()
{
return Status;
}
public String getDescription()
{
return Description;
}
And An Interface Class Called JsonPlaceHolderApi
public interface JsonPlaceHolderApi
{
#GET("admin")
Call<Login> getLogin();
#POST("admin")
Call<Login> createPost(#Body Login login);
}

Starting with the GET issue, you are getting fields (Username and password) equals to null because they are not at the top level of your JSON, so, in order to fix the GET issue you need to create the following class :
LoginResponse
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#SerializedName("Users")
User user;
#SerializedName("Status") int status;
#SerializedName("Description") String description;
}
Add a user class which will host all the user's data :
User
public class User {
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getClientno() {
return clientno;
}
public void setClientno(String clientno) {
this.clientno = clientno;
}
public String getCompanyno() {
return companyno;
}
public void setCompanyno(String companyno) {
this.companyno = companyno;
}
public String getUserno() {
return userno;
}
public void setUserno(String userno) {
this.userno = userno;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getRowno() {
return rowno;
}
public void setRowno(int rowno) {
this.rowno = rowno;
}
String clientno;
String companyno;
String userno;
String username;
String password;
int rowno;
}
Then update your JsonPlaceHolderApi interface to return a Call<LoginResponse> instead of Call<Login> :
#GET("admin")
Call<LoginResponse> getLogin();
#POST("admin")
Call<LoginResponse> createPost(#Body User login);
One more thing, replace both getLogin() and createPost() with the following :
private void getLogin() {
Call<LoginResponse> call = jsonPlaceHolderApi.getLogin();
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
http://retailapi.airtechsolutions.pk/api/login/admin#gmail.com/
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Error", t.getMessage());
}
});
}
private void createPost() {
User login = new User("New Name", "New Password");
Call<LoginResponse> call = jsonPlaceHolderApi.createPost(login);
call.enqueue(new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if (!response.isSuccessful()) {
Log.i("Code: ", String.valueOf(response.code()));
return;
}
LoginResponse loginResponse = response.body();
String content = "";
content += "Code: " + response.code() + "\n";
content += "UserName: " + loginResponse.user.getUsername() + "\n";
content += "Password: " + loginResponse.user.getPassword() + "\n";
content += "Status: " + loginResponse.getStatus() + "\n";
content += "Description: " + loginResponse.getDescription() + "\n\n";
Log.i("Read me", content);
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Log.i("Failure", t.getMessage());
}
});
}
For the POST issue, 405 (Method Not Allowed), it seems like the "admin" action doesn't support the POST method.

Related

Reading JSON - Retrofit - Android Studio

i really ned help with this. Im not being able to read the JSON and i dont know what im doing wrong.
I will drop my code here.
I have this Json
{
"id": "288",
"name": "Tarjeta Shopping",
"secure_thumbnail": "https://www.mercadopago.com/org-img/MP3/API/logos/288.gif",
"thumbnail": "http://img.mlstatic.com/org-img/MP3/API/logos/288.gif",
"processing_mode": "aggregator",
"merchant_account_id": null
}
This is my class that should represent that JSON
public class Tarjeta {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("secure_thumbnail")
#Expose
private String secureThumbnail;
#SerializedName("thumbnail")
#Expose
private String thumbnail;
#SerializedName("processing_mode")
#Expose
private String processingMode;
#SerializedName("merchant_account_id")
#Expose
private Object merchantAccountId;
public Tarjeta() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecureThumbnail() {
return secureThumbnail;
}
public void setSecureThumbnail(String secureThumbnail) {
this.secureThumbnail = secureThumbnail;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getProcessingMode() {
return processingMode;
}
public void setProcessingMode(String processingMode) {
this.processingMode = processingMode;
}
public Object getMerchantAccountId() {
return merchantAccountId;
}
public void setMerchantAccountId(Object merchantAccountId) {
this.merchantAccountId = merchantAccountId;
}
#Override
public String toString() {
return "Tarjeta{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", secureThumbnail='" + secureThumbnail + '\'' +
", thumbnail='" + thumbnail + '\'' +
", processingMode='" + processingMode + '\'' +
", merchantAccountId=" + merchantAccountId +
'}';
}
}
this is my GET method
#GET("payment_methods/card_issuers")
Call<Tarjeta> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);
And this is where i try to read it.
botonTest2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Test boton 2 clickeado");
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ServicePago servicePago = retrofit.create(ServicePago.class);
Call<Tarjeta> contenedorTarjetaCall = servicePago.getTarjetas2(apiKey,"visa");
contenedorTarjetaCall.enqueue(new Callback<Tarjeta>() {
#Override
public void onResponse(Call<Tarjeta> call, Response<Tarjeta> response) {
Toast.makeText(MainActivity.this, "BIEN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<Tarjeta> call, Throwable t) {
Toast.makeText(MainActivity.this, "ALGO SALIO MAL", Toast.LENGTH_SHORT).show();
}
});
}
});
Im habing this error: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
I think my class is correctly modelated, im completly lost.
since you did not post your entire JSON I'm going to answer with a rough idea hope it helps.
the error states that the received JSON is not a Tarjeta but an array of Tarjeta. so to fix it I guess you just have to wrap your response in a list type. so it goes something like this:
#GET("payment_methods/card_issuers")
Call<List<Tarjeta>> getTarjetas2(#Query("public_key") String apiKey,
#Query("payment_method_id") String payment_method_id);

how to get the specific value of JSON response from JAX-RS ?

I am using JAX-RS with jersey 1.6 to consume the API. i have so far been able to consume it but now i need some specific values only.
how i am consuming api:-
ClientResponse ebpResonse = ebpResource.type("application/json")
.header(HttpHeaders.AUTHORIZATION, token)
.post(ClientResponse.class, ebpReq1);
System.out.println("ebp response is: " + ebpResonse.getEntity(String.class));
i receive response which looks like this:-
{
"code": "2075-4673",
"data": {
"requestId": 4673,
"requestCode": "2075-4673",
"fiscalYear": {
"fiscalYearId": 2075,
"fiscalYearCode": "2075/76"
},
"requestDate": 1531851300000,
"requestNdate": "2075/04/02",
"rcAgency": {
"id": 2373,
"code": "210003501",
"rcAgencyEDesc": "ABC",
"rcAgencyNDesc": " सेवा ",
"nepaliName": " सेवा",
"engishName": null
},
"status": 1,
"pan": "500127108",
"payerCode": null,
"payerEdesc": "ABC Enterprises",
"payerNdesc": null,
"payerAddress": null,
"payerPhone": null,
"totalAmount": 14000,
"createdBy": "psctest",
"createdOn": 1531851300000,
"collectedBank": null,
"collectedDate": null,
"collectedBy": null,
"token": "xxxxxxxxxxxxxxxx",
"details": [
{
"ebpNo": "4977",
"sno": 1,
"depositSlipNo": null,
"purpose": null,
"revenueHead": {
"id": 14224,
"code": "14224",
"oldCode": "14224",
"nepaliName": "शुल्क",
"englishName": "शुल्क",
"description": "शुल्क",
"nepaliDescription": "शुल्क",
"preRevenueHeadId": 0,
"status": true,
"federal": true,
"state": true,
"local": true,
"remarks": "xxxxx"
},
"remarks": "remarks",
"description": "Production",
"currency": {
"currencyId": 524,
"currencyCode": "524",
"descEnglish": "NRS",
"descNepali": "NRS"
},
"amount": 14000,
"taxAdv": false,
"taxyearId": 2074,
"dueAmount": 14000,
"createdBy": "psctest",
"createdOn": 1531894162000
}
]
},
"message": "Voucher has saved sucessfully.",
"token": "xxxxxxxxxxxxxxxxxxxx",
"status": 0
}
this response for me contains too many unnecessary information too. i need to get epbNo, token, pan in some separate variable. how can i achieve it ?
Here you go
1- Json Abstract class
package test;
import com.google.gson.Gson;
public abstract class JsonObject {
#Override
public String toString() {
Gson gson = new Gson();
return gson.toJson(this);
}
public Object toObject(String json){
Gson gson = new Gson();
return gson.fromJson(json, this.getClass());
}
}
2- Detail class
package test;
public class Detail extends JsonObject {
private String ebpNo;
private float sno;
private String depositSlipNo = null;
private String purpose = null;
RevenueHead RevenueHeadObject;
private String remarks;
private String description;
Currency CurrencyObject;
private float amount;
private boolean taxAdv;
private float taxyearId;
private float dueAmount;
private String createdBy;
private float createdOn;
// Getter Methods
public String getEbpNo() {
return ebpNo;
}
public float getSno() {
return sno;
}
public String getDepositSlipNo() {
return depositSlipNo;
}
public String getPurpose() {
return purpose;
}
public RevenueHead getRevenueHead() {
return RevenueHeadObject;
}
public String getRemarks() {
return remarks;
}
public String getDescription() {
return description;
}
public Currency getCurrency() {
return CurrencyObject;
}
public float getAmount() {
return amount;
}
public boolean getTaxAdv() {
return taxAdv;
}
public float getTaxyearId() {
return taxyearId;
}
public float getDueAmount() {
return dueAmount;
}
public String getCreatedBy() {
return createdBy;
}
public float getCreatedOn() {
return createdOn;
}
// Setter Methods
public void setEbpNo(String ebpNo) {
this.ebpNo = ebpNo;
}
public void setSno(float sno) {
this.sno = sno;
}
public void setDepositSlipNo(String depositSlipNo) {
this.depositSlipNo = depositSlipNo;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public void setRevenueHead(RevenueHead revenueHeadObject) {
this.RevenueHeadObject = revenueHeadObject;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public void setDescription(String description) {
this.description = description;
}
public void setCurrency(Currency currencyObject) {
this.CurrencyObject = currencyObject;
}
public void setAmount(float amount) {
this.amount = amount;
}
public void setTaxAdv(boolean taxAdv) {
this.taxAdv = taxAdv;
}
public void setTaxyearId(float taxyearId) {
this.taxyearId = taxyearId;
}
public void setDueAmount(float dueAmount) {
this.dueAmount = dueAmount;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public void setCreatedOn(float createdOn) {
this.createdOn = createdOn;
}
}
class Currency extends JsonObject {
private float currencyId;
private String currencyCode;
private String descEnglish;
private String descNepali;
// Getter Methods
public float getCurrencyId() {
return currencyId;
}
public String getCurrencyCode() {
return currencyCode;
}
public String getDescEnglish() {
return descEnglish;
}
public String getDescNepali() {
return descNepali;
}
// Setter Methods
public void setCurrencyId(float currencyId) {
this.currencyId = currencyId;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
public void setDescEnglish(String descEnglish) {
this.descEnglish = descEnglish;
}
public void setDescNepali(String descNepali) {
this.descNepali = descNepali;
}
}
class RevenueHead extends JsonObject {
private float id;
private String code;
private String oldCode;
private String nepaliName;
private String englishName;
private String description;
private String nepaliDescription;
private float preRevenueHeadId;
private boolean status;
private boolean federal;
private boolean state;
private boolean local;
private String remarks;
// Getter Methods
public float getId() {
return id;
}
public String getCode() {
return code;
}
public String getOldCode() {
return oldCode;
}
public String getNepaliName() {
return nepaliName;
}
public String getEnglishName() {
return englishName;
}
public String getDescription() {
return description;
}
public String getNepaliDescription() {
return nepaliDescription;
}
public float getPreRevenueHeadId() {
return preRevenueHeadId;
}
public boolean getStatus() {
return status;
}
public boolean getFederal() {
return federal;
}
public boolean getState() {
return state;
}
public boolean getLocal() {
return local;
}
public String getRemarks() {
return remarks;
}
// Setter Methods
public void setId(float id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setOldCode(String oldCode) {
this.oldCode = oldCode;
}
public void setNepaliName(String nepaliName) {
this.nepaliName = nepaliName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public void setDescription(String description) {
this.description = description;
}
public void setNepaliDescription(String nepaliDescription) {
this.nepaliDescription = nepaliDescription;
}
public void setPreRevenueHeadId(float preRevenueHeadId) {
this.preRevenueHeadId = preRevenueHeadId;
}
public void setStatus(boolean status) {
this.status = status;
}
public void setFederal(boolean federal) {
this.federal = federal;
}
public void setState(boolean state) {
this.state = state;
}
public void setLocal(boolean local) {
this.local = local;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
3- TestDTO class
/**
*
*/
package test;
import java.util.ArrayList;
/**
* #author 00990
*
*/
public class TestDTO extends JsonObject {
private String code;
Data data;
private String message;
private String token;
private float status;
// Getter Methods
public String getCode() {
return code;
}
public Data getData() {
return data;
}
public String getMessage() {
return message;
}
public String getToken() {
return token;
}
public float getStatus() {
return status;
}
// Setter Methods
public void setCode(String code) {
this.code = code;
}
public void setData(Data dataObject) {
this.data = dataObject;
}
public void setMessage(String message) {
this.message = message;
}
public void setToken(String token) {
this.token = token;
}
public void setStatus(float status) {
this.status = status;
}
public static void main(String[] args) {
String jsonObj = "{\r\n" + " \"code\": \"2075-4673\",\r\n" + " \"data\": {\r\n"
+ " \"requestId\": 4673,\r\n" + " \"requestCode\": \"2075-4673\",\r\n"
+ " \"fiscalYear\": {\r\n" + " \"fiscalYearId\": 2075,\r\n"
+ " \"fiscalYearCode\": \"2075/76\"\r\n" + " },\r\n"
+ " \"requestDate\": 1531851300000,\r\n" + " \"requestNdate\": \"2075/04/02\",\r\n"
+ " \"rcAgency\": {\r\n" + " \"id\": 2373,\r\n"
+ " \"code\": \"210003501\",\r\n" + " \"rcAgencyEDesc\": \"ABC\",\r\n"
+ " \"rcAgencyNDesc\": \" सेवा \",\r\n" + " \"nepaliName\": \" सेवा\",\r\n"
+ " \"engishName\": null\r\n" + " },\r\n" + " \"status\": 1,\r\n"
+ " \"pan\": \"500127108\",\r\n" + " \"payerCode\": null,\r\n"
+ " \"payerEdesc\": \"ABC Enterprises\",\r\n" + " \"payerNdesc\": null,\r\n"
+ " \"payerAddress\": null,\r\n" + " \"payerPhone\": null,\r\n"
+ " \"totalAmount\": 14000,\r\n" + " \"createdBy\": \"psctest\",\r\n"
+ " \"createdOn\": 1531851300000,\r\n" + " \"collectedBank\": null,\r\n"
+ " \"collectedDate\": null,\r\n" + " \"collectedBy\": null,\r\n"
+ " \"token\": \"xxxxxxxxxxxxxxxx\",\r\n" + " \"details\": [\r\n" + " {\r\n"
+ " \"ebpNo\": \"4977\",\r\n" + " \"sno\": 1,\r\n"
+ " \"depositSlipNo\": null,\r\n" + " \"purpose\": null,\r\n"
+ " \"revenueHead\": {\r\n" + " \"id\": 14224,\r\n"
+ " \"code\": \"14224\",\r\n" + " \"oldCode\": \"14224\",\r\n"
+ " \"nepaliName\": \"शुल्क\",\r\n"
+ " \"englishName\": \"शुल्क\",\r\n"
+ " \"description\": \"शुल्क\",\r\n"
+ " \"nepaliDescription\": \"शुल्क\",\r\n"
+ " \"preRevenueHeadId\": 0,\r\n" + " \"status\": true,\r\n"
+ " \"federal\": true,\r\n" + " \"state\": true,\r\n"
+ " \"local\": true,\r\n" + " \"remarks\": \"xxxxx\"\r\n"
+ " },\r\n" + " \"remarks\": \"remarks\",\r\n"
+ " \"description\": \"Production\",\r\n" + " \"currency\": {\r\n"
+ " \"currencyId\": 524,\r\n" + " \"currencyCode\": \"524\",\r\n"
+ " \"descEnglish\": \"NRS\",\r\n"
+ " \"descNepali\": \"NRS\"\r\n" + " },\r\n"
+ " \"amount\": 14000,\r\n" + " \"taxAdv\": false,\r\n"
+ " \"taxyearId\": 2074,\r\n" + " \"dueAmount\": 14000,\r\n"
+ " \"createdBy\": \"psctest\",\r\n" + " \"createdOn\": 1531894162000\r\n"
+ " }\r\n" + " ]\r\n" + " },\r\n"
+ " \"message\": \"Voucher has saved sucessfully.\",\r\n"
+ " \"token\": \"xxxxxxxxxxxxxxxxxxxx\",\r\n" + " \"status\": 0\r\n" + "}";
System.out.println("Token :" +((TestDTO) new TestDTO().toObject(jsonObj)).getToken());
System.out.println(" PAN :" +((TestDTO) new TestDTO().toObject(jsonObj)).getData().getPan());
System.out.println("EBPNo :" +((TestDTO) new TestDTO().toObject(jsonObj)).getData().getDetails().get(0).getEbpNo());
}
}
class Data extends JsonObject {
private float requestId;
private String requestCode;
FiscalYear FiscalYearObject;
private float requestDate;
private String requestNdate;
RcAgency RcAgencyObject;
private float status;
private String pan;
private String payerCode = null;
private String payerEdesc;
private String payerNdesc = null;
private String payerAddress = null;
private String payerPhone = null;
private float totalAmount;
private String createdBy;
private float createdOn;
private String collectedBank = null;
private String collectedDate = null;
private String collectedBy = null;
private String token;
ArrayList<Detail> details = new ArrayList<Detail>();
// Getter Methods
public float getRequestId() {
return requestId;
}
public ArrayList<Detail> getDetails() {
return details;
}
public void addToDetails(Detail detail) {
if (details == null) {
details = new ArrayList<Detail>();
}
this.details.add(detail);
}
public String getRequestCode() {
return requestCode;
}
public FiscalYear getFiscalYear() {
return FiscalYearObject;
}
public float getRequestDate() {
return requestDate;
}
public String getRequestNdate() {
return requestNdate;
}
public RcAgency getRcAgency() {
return RcAgencyObject;
}
public float getStatus() {
return status;
}
public String getPan() {
return pan;
}
public String getPayerCode() {
return payerCode;
}
public String getPayerEdesc() {
return payerEdesc;
}
public String getPayerNdesc() {
return payerNdesc;
}
public String getPayerAddress() {
return payerAddress;
}
public String getPayerPhone() {
return payerPhone;
}
public float getTotalAmount() {
return totalAmount;
}
public String getCreatedBy() {
return createdBy;
}
public float getCreatedOn() {
return createdOn;
}
public String getCollectedBank() {
return collectedBank;
}
public String getCollectedDate() {
return collectedDate;
}
public String getCollectedBy() {
return collectedBy;
}
public String getToken() {
return token;
}
// Setter Methods
public void setRequestId(float requestId) {
this.requestId = requestId;
}
public void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}
public void setFiscalYear(FiscalYear fiscalYearObject) {
this.FiscalYearObject = fiscalYearObject;
}
public void setRequestDate(float requestDate) {
this.requestDate = requestDate;
}
public void setRequestNdate(String requestNdate) {
this.requestNdate = requestNdate;
}
public void setRcAgency(RcAgency rcAgencyObject) {
this.RcAgencyObject = rcAgencyObject;
}
public void setStatus(float status) {
this.status = status;
}
public void setPan(String pan) {
this.pan = pan;
}
public void setPayerCode(String payerCode) {
this.payerCode = payerCode;
}
public void setPayerEdesc(String payerEdesc) {
this.payerEdesc = payerEdesc;
}
public void setPayerNdesc(String payerNdesc) {
this.payerNdesc = payerNdesc;
}
public void setPayerAddress(String payerAddress) {
this.payerAddress = payerAddress;
}
public void setPayerPhone(String payerPhone) {
this.payerPhone = payerPhone;
}
public void setTotalAmount(float totalAmount) {
this.totalAmount = totalAmount;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public void setCreatedOn(float createdOn) {
this.createdOn = createdOn;
}
public void setCollectedBank(String collectedBank) {
this.collectedBank = collectedBank;
}
public void setCollectedDate(String collectedDate) {
this.collectedDate = collectedDate;
}
public void setCollectedBy(String collectedBy) {
this.collectedBy = collectedBy;
}
public void setToken(String token) {
this.token = token;
}
}
class RcAgency extends JsonObject {
private float id;
private String code;
private String rcAgencyEDesc;
private String rcAgencyNDesc;
private String nepaliName;
private String engishName = null;
// Getter Methods
public float getId() {
return id;
}
public String getCode() {
return code;
}
public String getRcAgencyEDesc() {
return rcAgencyEDesc;
}
public String getRcAgencyNDesc() {
return rcAgencyNDesc;
}
public String getNepaliName() {
return nepaliName;
}
public String getEngishName() {
return engishName;
}
// Setter Methods
public void setId(float id) {
this.id = id;
}
public void setCode(String code) {
this.code = code;
}
public void setRcAgencyEDesc(String rcAgencyEDesc) {
this.rcAgencyEDesc = rcAgencyEDesc;
}
public void setRcAgencyNDesc(String rcAgencyNDesc) {
this.rcAgencyNDesc = rcAgencyNDesc;
}
public void setNepaliName(String nepaliName) {
this.nepaliName = nepaliName;
}
public void setEngishName(String engishName) {
this.engishName = engishName;
}
}
class FiscalYear extends JsonObject {
private float fiscalYearId;
private String fiscalYearCode;
// Getter Methods
public float getFiscalYearId() {
return fiscalYearId;
}
public String getFiscalYearCode() {
return fiscalYearCode;
}
// Setter Methods
public void setFiscalYearId(float fiscalYearId) {
this.fiscalYearId = fiscalYearId;
}
public void setFiscalYearCode(String fiscalYearCode) {
this.fiscalYearCode = fiscalYearCode;
}
}
4- Run TestDTO class, here is the output
Token :xxxxxxxxxxxxxxxxxxxx PAN :500127108 EBPNo :4977
Just maintain null values in your code, and import gson-2.7.jar

Retrofit2 POST Request, null values in data reponse

I have some issues with Retrofit2 while posting data to an API using POST request.
The response from the server is successful but all the values displayed on the response are null :
I/SUCCESS: test : Post{id='null', titre='null', description='null', prix='null', pseudo='null', emailContact='null', telContact='null', ville='null', cp='null', image='null', date='null'}
Here is an example of the JSON that I've to receive
{
"success": true,
"response": {
"id": “5a5f11196c2aa”,
"titre": "Vends 406",
"description": "Pas chere",
"prix": "4500",
"pseudo": "jml",
"emailContact": "",
"telContact": "Vends 406",
"ville": "",
"cp": "",
"images": [],
"date": 1516179737
}
}
Here is my data model :
public class Post {
#SerializedName("cp")
private String cp;
#SerializedName("date")
private Long date;
#SerializedName("description")
private String description;
#SerializedName("emailContact")
private String emailContact;
#SerializedName("id")
private String id;
#SerializedName("images")
private String[] images;
#SerializedName("prix")
private String prix;
#SerializedName("pseudo")
private String pseudo;
#SerializedName("telContact")
private String telContact;
#SerializedName("titre")
private String titre;
#SerializedName("ville")
private String ville;
public String getCp() {
return cp;
}
public void setCp(String cp) {
this.cp = cp;
}
public Long getDate() {
return date;
}
public void setDate(Long date) {
this.date = date;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getEmailContact() {
return emailContact;
}
public void setEmailContact(String emailContact) {
this.emailContact = emailContact;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String[] getImages() {
return images;
}
public void setImages(String[] images) {
this.images = images;
}
public String getPrix() {
return prix;
}
public void setPrix(String prix) {
this.prix = prix;
}
public String getPseudo() {
return pseudo;
}
public void setPseudo(String pseudo) {
this.pseudo = pseudo;
}
public String getTelContact() {
return telContact;
}
public void setTelContact(String telContact) {
this.telContact = telContact;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
#Override
public String toString(){
return "Post{" +
"id='" + getId() + '\'' +
", titre='" + getTitre() + '\'' +
", description='" + getDescription() + '\'' +
", prix='" + getPrix() + '\'' +
", pseudo='" + getPseudo() + '\'' +
", emailContact='" + getEmailContact() + '\'' +
", telContact='" + getTelContact() + '\'' +
", ville='" + getVille() + '\'' +
", cp='" + getCp() + '\'' +
", image='" + getImages() + '\'' +
", date='" + getDate() + '\'' +
'}';
}}
Here is my Retrofit Instance :
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
.build();
Here is my API Service Interface :
public interface APIService {
#POST("/android-api")
#FormUrlEncoded
Call<Post> savePost(#Field("apikey") String apikey,
#Field("method") String method,
#Field("titre") String title,
#Field("description") String description,
#Field("prix") String prix,
#Field("pseudo") String pseudo,
#Field("emailContact") String emailContact,
#Field("telContact") String telContact,
#Field("ville") String ville,
#Field("cp") String cp,
#Field("images") String[] images
);}
And here is my sendPost method :
public void sendPost(String title, String prix, String cp, String ville, String description) {
// On récupère ici les préférences de l'utilisateur
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String pseudo = preferences.getString("pseudo", "DEFAULT");
String emailContact = preferences.getString("mail", "DEFAULT");
String telContact = preferences.getString("tel", "DEFAULT");
// Provisoire
String[] images = {} ;
mAPIService.savePost(APIKEY,METHOD,title,description,prix,pseudo,emailContact,telContact,ville,cp,images).enqueue(new Callback<Post>() {
#Override
public void onResponse(Call<Post> call, Response<Post> response) {
if(response.isSuccessful()) {
showResponse(response.body().toString());
Log.i("SUCCESS", "test : "+ response.body().toString());
}
}
#Override
public void onFailure(Call<Post> call, Throwable t) {
Log.e("FAIL", "Unable to submit post to API.");
}
});}
Thank you in advance for helping me
I recently used retrofit to retrieve data...
First used http://www.jsonschema2pojo.org/ to create a model class from your possible outcome JSON response .
And I used Retrofit instance--
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client =
new OkHttpClient.Builder().addInterceptor(interceptor).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();

Android - java Cloud Firestore : NullPointerException when converting data toObject [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
This is what my Firestore data structure looks like
Hello, i have an issue and i have searched online but nothing seem to come close to what am facing. i am using firestore to store my data
This is the users node.
user section
And this is the user_account_settings node.
user_account_settings section
The goal is to loop through these nodes and retrieve/get data from the node and set them into text and display them using custom models.
this is the model for Account settings
public class UserAccountSettings {
private String description;
private String display_name;
private long followers;
private long following;
private long posts;
private String profile_photo;
private String username;
private String website;
public UserAccountSettings(String description, String display_name, long followers, long following,
long posts, String profile_photo, String username, String website) {
this.description = description;
this.display_name = display_name;
this.followers = followers;
this.following = following;
this.posts = posts;
this.profile_photo = profile_photo;
this.username = username;
this.website = website;
}
public UserAccountSettings(){
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getDisplay_name() {
return display_name;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public long getFollowers() {
return followers;
}
public void setFollowers(long followers) {
this.followers = followers;
}
public long getFollowing() {
return following;
}
public void setFollowing(long following) {
this.following = following;
}
public long getPosts() {
return posts;
}
public void setPosts(long posts) {
this.posts = posts;
}
public String getProfile_photo() {
return profile_photo;
}
public void setProfile_photo(String profile_photo) {
this.profile_photo = profile_photo;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
#Override
public String toString() {
return "UserAccountSettings{" +
"description='" + description + '\'' +
", display_name='" + display_name + '\'' +
", followers=" + followers +
", following=" + following +
", posts=" + posts +
", profile_photo='" + profile_photo + '\'' +
", username='" + username + '\'' +
", website='" + website + '\'' +
'}';
}
}
and user model
public class User {
private String user_id;
private long phone_number;
private String email;
private String username;
public User(String user_id, long phone_number, String email, String username) {
this.user_id = user_id;
this.phone_number = phone_number;
this.email = email;
this.username = username;
}
public User(){
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public long getPhone_number() {
return phone_number;
}
public void setPhone_number(long phone_number) {
this.phone_number = phone_number;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "User{" +
"user_id='" + user_id + '\'' +
", phone_number='" + phone_number + '\'' +
", email='" + email + '\'' +
", username='" + username + '\'' +
'}';
}
}
User settings (Holding both user and user_account_settings)
public class UserSettings {
//for handling multilple queries in database : users and user_account_settings.
private User user;
private UserAccountSettings settings;
public UserSettings(User user, UserAccountSettings settings) {
this.user = user;
this.settings = settings;
}
public UserSettings(ArrayList<User> mUser, ArrayList<UserAccountSettings> mSettings){
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserAccountSettings getSettings() {
return settings;
}
public void setSettings(UserAccountSettings settings) {
this.settings = settings;
}
#Override
public String toString() {
return "UserSettings{" +
"user=" + user +
", settings=" + settings +
'}';
}
}
trying to retrieve and set the data from firestore to the models
public UserSettings getUserSettings(final DocumentSnapshot documentSnapshot){
Log.d(TAG, "getUserSettings: retrieving user account settings from firestore");
final ArrayList<UserAccountSettings> mSettings = new ArrayList<>();
final ArrayList<User> mUser = new ArrayList<>();
//handling user_account_settings_node.
mFirestore.collection("user_account_settings").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: FirebaseFirestoreException", e);
return;
}
for (DocumentSnapshot document : documentSnapshots) {
Log.d(TAG, document.getId() + " => " + document.getData());
if (document.getId().equals("user_account_settings")){
Log.d(TAG, "checking if id equals user_account_settings: yes, it does");
Log.d(TAG, "onSuccess: Document" + document.getId() + ";" + document.getData());
UserAccountSettings settings = document.toObject(UserAccountSettings.class);
Log.d(TAG, "UserAccountSettings: " + "username is" + settings.getUsername());
settings.setDisplay_name(documentSnapshot.getString("display_name"));
settings.setUsername(documentSnapshot.getString("username"));
settings.setWebsite(documentSnapshot.getString("website"));
settings.setProfile_photo(documentSnapshot.getString("profile_photo"));
settings.setPosts(documentSnapshot.getLong("posts"));
settings.setFollowers(documentSnapshot.getLong("followers"));
settings.setFollowing(documentSnapshot.getLong("following"));
mSettings.add(settings);
}
}
}
});
//handling users node.
mFirestore.collection("users").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshots) {
Log.d(TAG, document.getId() + " => " + document.getData());
if (document.getId().equals(mContext.getString(R.string.dbname_users))){
Log.d(TAG, "checking if id equals user_account_settings: yes, it does");
Log.d(TAG, "onSuccess: Document" + document.getId() + ";" + document.getData());
User user = document.toObject(User.class);
Log.d(TAG, "user: got the user information" + "user I.D is "+ user.getUser_id());
user.setUsername(documentSnapshot.getString("username"));
user.setEmail(documentSnapshot.getString("email"));
user.setPhone_number(documentSnapshot.getLong("phone_number"));
user.setUser_id(documentSnapshot.getString("user_id"));
mUser.add(user);
}
}
}
});
return new UserSettings(mUser, mSettings );
}
and i try getting these data from the documents
//setting Profile Widgets
private void setProfileWidgets(UserSettings userSettings){
Log.d(TAG, "setProfileWidgets: Setting widgets with data retrieved from firebase firestore" + userSettings.toString());
Log.d(TAG, "setProfileWidgets: searching for username" + userSettings.getSettings().getUsername());
User user = userSettings.getUser();
UserAccountSettings settings = userSettings.getSettings();
try {
UniversalImageLoader.setSingleImage(settings.getProfile_photo(), mProfilePhoto, null, "");
mDisplayname.setText(settings.getDisplay_name());
mUsername.setText(settings.getUsername());
mWebsite.setText(settings.getWebsite());
mDescription.setText(settings.getDescription());
mPosts.setText(String.valueOf(settings.getPosts()));
mFollowers.setText(String.valueOf(settings.getFollowers()));
mFollowing.setText(String.valueOf(settings.getFollowing()));
mProgressBar.setVisibility(View.GONE);
}
catch (NullPointerException e){
Log.e(TAG, "setProfileWidgets: NullPointerException" + e.getMessage());
}
}
then i initialize the widgets
mFirebaseFirestore = FirebaseFirestore.getInstance();
myUserRef = mFirebaseFirestore.collection("users");
myUserSettingsRef = mFirebaseFirestore.collection("user_account_settings");
myUserSettingsRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshot) {
Log.d(TAG, document.getId() + " => " + document.getData());
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(document));
}
}
});
myUserRef.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null){
Log.w(TAG, "onEvent: ", e);
return;
}
for (DocumentSnapshot document : documentSnapshot) {
Log.d(TAG, document.getId() + " => " + document.getData());
//retrieve user information from the database
setProfileWidgets(mFirebaseMethods.getUserSettings(document));
}
}
});
When i run the app, this is what i get
error message
if you see the code, i can see other user information. but it throws me a null pointer exception on my widgets (user=null , settings=null). i have gone through all the widgets id's and its correct am wondering if someone can point out where am getting wrong. thanks in advance
The UserSettings class has a constructor that looks like this:
public UserSettings(ArrayList<User> mUser, ArrayList<UserAccountSettings> mSettings){
}
This constructor doesn't set the user and settings variables defined in this class and it is the constructor you use to create the return value of the getUserSettings method.
return new UserSettings(mUser, mSettings ); // `mUser` and `mSettings` are `ArrayList`s
Hence the exception.
This is the main problem, the one that generates the exception you've mentioned but it is not the only problem.

Expected BEGIN_OBJECT but was STRING at line 1 column 1 GSON

I am getting this error when querying a URL and get a json object. My json:
{"status":1,"username":"admin","nombre":"Username","email":"example#example.cl","codigo_usuario":"1","hash":"2938632bfdklsngh","imagen":"05c151584cc1e9aa2985b5bd0a3a4cd2.jpeg"}
Create the User class
public class User {
private int status;
private String username;
private String nombre;
private String email;
private String codigo_usuario;
private String hash;
private String imagen;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
public String getCodigo_usuario() {
return codigo_usuario;
}
public void setCodigo_usuario(String codigo_usuario) {
this.codigo_usuario = codigo_usuario;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User [status=" + status + ", username=" + username
+ ", nombre=" + nombre + ", email=" + email
+ ", codigo_usuario=" + codigo_usuario + ", hash=" + hash
+ ", imagen=" + imagen + "]";
}
}
And in my class, I make the request to the URL I have this code:
public static boolean authenticate(String username, String password){
boolean error = false;
User user = null;
try {
String request = Config.getText("URL_BASE")+Config.getText("URL_AUTHENTICATE")+username+"/"+password;
HttpURLConnection conn = (HttpURLConnection) new URL(request).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new Exception("Failed : HTTP error code : " + conn.getResponseCode());
}
user = new Gson().fromJson(new InputStreamReader(conn.getInputStream()), User.class);
System.out.println(user.toString());
conn.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return error;
}
And I get the exception. I saw other post with this same error and in most the error was the json format or class that did not have the same fields. Now, check well and everything should be OK. But for some reason I receive this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
at com.google.gson.Gson.fromJson(Gson.java:741)
at controller.WService.authenticate(WService.java:29)
at view.Login._verificarLogin(Login.java:77)
at view.Login$2.actionPerformed(Login.java:44)
I'm new to Java and try to consume a web service for data and use. I think this is my best option but still do not understand the error.

Categories