How to access Serializable object in android - android

I am using Serializable interface to send user defined data from one activity to another.
Here is my code :
TasksheetData[] alltasks = new TasksheetData();
Intent in=new Intent(TaskSheetList.this, TaskDetails.class);
in.putExtra("TaskSheetData", alltasks);
and in other activity I am accessing this object like :
TasksheetData tData = (TasksheetData) getIntent().getSerializableExtra("TaskSheetData");
and here is my TasksheetData class
#SuppressWarnings("serial")
public class TasksheetData implements Serializable {
private int TaskID;
private int AttendantID;
private String AttendentName;
private String ReservationID;
private String ResStatusCode;
private int InspectionStartedById;
private String HKStatusCode;
private int FOStatusID;
private String FOStatusCode;
private int JobStatusID;
private String JobStatusCode;
private int LocationID;
private String LocationName;
private int RoomTypeID;
private String RoomType;
private int SectionID;
private String GuestID;
private String GuestName;
private String VIPCode;
private String Pax;
private String ArrivalTime;
private String CheckInTime;
private String CheckOutTime;
private String QueueSince;
private Trace[] arrTraces;
private String Specials;
private String ReservationComments;
private String SupervisorComments;
private String HKNotes;
private String TaskSheetName;
private int StandardCleaningTime;
private int AttendantPriority;
private String SupervisorPriority;
private String TaskStartTime;
private String TaskEndTime;
private String TasksheetInstruction;
private String localJobStatusCode;
private Boolean isSynch;
private String credit;
private String RemainingTimeSec;
private String TaskTypeId;
private String AttendantCLTypeId, SupervisorCLTypeId;
private String TritonLocationID;
private String PendingTritonJob;
private Boolean isDiscrepancy, InspectionStatus, IsTaskInspected;
public int getTaskID() {
return TaskID;
}
public void setTaskID(int taskID) {
TaskID = taskID;
}
public int getAttendantID() {
return AttendantID;
}
public void setAttendantID(int attendantID) {
AttendantID = attendantID;
}
public String getAttendentName() {
return AttendentName;
}
public void setAttendentName(String attendentName) {
AttendentName = attendentName;
}
public String getReservationID() {
return ReservationID;
}
public void setReservationID(String reservationID) {
ReservationID = reservationID;
}
public String getResStatusCode() {
return ResStatusCode;
}
public void setResStatusCode(String resStatusCode) {
ResStatusCode = resStatusCode;
}
public int getInspectionStartedById() {
return InspectionStartedById;
}
public void setInspectionStartedById(int inspectionStartedById) {
InspectionStartedById = inspectionStartedById;
}
public String getHKStatusCode() {
return HKStatusCode;
}
public void setHKStatusCode(String hKStatusCode) {
HKStatusCode = hKStatusCode;
}
public int getFOStatusID() {
return FOStatusID;
}
public void setFOStatusID(int fOStatusID) {
FOStatusID = fOStatusID;
}
public String getFOStatusCode() {
return FOStatusCode;
}
public void setFOStatusCode(String fOStatusCode) {
FOStatusCode = fOStatusCode;
}
public int getJobStatusID() {
return JobStatusID;
}
public void setJobStatusID(int jobStatusID) {
JobStatusID = jobStatusID;
}
public String getJobStatusCode() {
return JobStatusCode;
}
public void setJobStatusCode(String jobStatusCode) {
JobStatusCode = jobStatusCode;
}
public int getLocationID() {
return LocationID;
}
public void setLocationID(int locationID) {
LocationID = locationID;
}
public String getLocationName() {
return LocationName;
}
public void setLocationName(String locationName) {
LocationName = locationName;
}
public int getRoomTypeID() {
return RoomTypeID;
}
public void setRoomTypeID(int roomTypeID) {
RoomTypeID = roomTypeID;
}
public String getRoomType() {
return RoomType;
}
public void setRoomType(String roomType) {
RoomType = roomType;
}
public int getSectionID() {
return SectionID;
}
public void setSectionID(int sectionID) {
SectionID = sectionID;
}
public String getGuestID() {
return GuestID;
}
public void setGuestID(String guestID) {
GuestID = guestID;
}
public String getGuestName() {
return GuestName;
}
public void setGuestName(String guestName) {
GuestName = guestName;
}
public String getVIPCode() {
return VIPCode;
}
public void setVIPCode(String vIPCode) {
VIPCode = vIPCode;
}
public String getPax() {
return Pax;
}
public void setPax(String pax) {
Pax = pax;
}
public String getArrivalTime() {
return ArrivalTime;
}
public void setArrivalTime(String arrivalTime) {
ArrivalTime = arrivalTime;
}
public String getCheckInTime() {
return CheckInTime;
}
public void setCheckInTime(String checkInTime) {
CheckInTime = checkInTime;
}
public String getCheckOutTime() {
return CheckOutTime;
}
public void setCheckOutTime(String checkOutTime) {
CheckOutTime = checkOutTime;
}
public String getQueueSince() {
return QueueSince;
}
public void setQueueSince(String queueSince) {
QueueSince = queueSince;
}
public Trace[] getArrTraces() {
return arrTraces;
}
public void setArrTraces(Trace[] arrTraces) {
this.arrTraces = arrTraces;
}
public String getSpecials() {
return Specials;
}
public void setSpecials(String specials) {
Specials = specials;
}
public String getReservationComments() {
return ReservationComments;
}
public void setReservationComments(String reservationComments) {
ReservationComments = reservationComments;
}
public String getSupervisorComments() {
return SupervisorComments;
}
public void setSupervisorComments(String supervisorComments) {
SupervisorComments = supervisorComments;
}
public String getHKNotes() {
return HKNotes;
}
public void setHKNotes(String hKNotes) {
HKNotes = hKNotes;
}
public String getTaskSheetName() {
return TaskSheetName;
}
public void setTaskSheetName(String taskSheetName) {
TaskSheetName = taskSheetName;
}
public int getStandardCleaningTime() {
return StandardCleaningTime;
}
public void setStandardCleaningTime(int standardCleaningTime) {
StandardCleaningTime = standardCleaningTime;
}
public int getAttendantPriority() {
return AttendantPriority;
}
public void setAttendantPriority(int attendantPriority) {
AttendantPriority = attendantPriority;
}
public String getSupervisorPriority() {
return SupervisorPriority;
}
public void setSupervisorPriority(String supervisorPriority) {
SupervisorPriority = supervisorPriority;
}
public String getTaskStartTime() {
return TaskStartTime;
}
public void setTaskStartTime(String taskStartTime) {
TaskStartTime = taskStartTime;
}
public String getTaskEndTime() {
return TaskEndTime;
}
public void setTaskEndTime(String taskEndTime) {
TaskEndTime = taskEndTime;
}
public String getTasksheetInstruction() {
return TasksheetInstruction;
}
public void setTasksheetInstruction(String tasksheetInstruction) {
TasksheetInstruction = tasksheetInstruction;
}
public String getLocalJobStatusCode() {
return localJobStatusCode;
}
public void setLocalJobStatusCode(String localJobStatusCode) {
this.localJobStatusCode = localJobStatusCode;
}
public Boolean getIsSynch() {
return isSynch;
}
public void setIsSynch(Boolean isSynch) {
this.isSynch = isSynch;
}
public String getCredit() {
return credit;
}
public void setCredit(String credit) {
this.credit = credit;
}
public String getRemainingTimeSec() {
return RemainingTimeSec;
}
public void setRemainingTimeSec(String remainingTimeSec) {
RemainingTimeSec = remainingTimeSec;
}
public String getTaskTypeId() {
return TaskTypeId;
}
public void setTaskTypeId(String taskTypeId) {
TaskTypeId = taskTypeId;
}
public String getAttendantCLTypeId() {
return AttendantCLTypeId;
}
public void setAttendantCLTypeId(String attendantCLTypeId) {
AttendantCLTypeId = attendantCLTypeId;
}
public String getSupervisorCLTypeId() {
return SupervisorCLTypeId;
}
public void setSupervisorCLTypeId(String supervisorCLTypeId) {
SupervisorCLTypeId = supervisorCLTypeId;
}
public String getTritonLocationID() {
return TritonLocationID;
}
public void setTritonLocationID(String tritonLocationID) {
TritonLocationID = tritonLocationID;
}
public String getPendingTritonJob() {
return PendingTritonJob;
}
public void setPendingTritonJob(String pendingTritonJob) {
PendingTritonJob = pendingTritonJob;
}
public Boolean getIsDiscrepancy() {
return isDiscrepancy;
}
public void setIsDiscrepancy(Boolean isDiscrepancy) {
this.isDiscrepancy = isDiscrepancy;
}
public Boolean getInspectionStatus() {
return InspectionStatus;
}
public void setInspectionStatus(Boolean inspectionStatus) {
InspectionStatus = inspectionStatus;
}
public Boolean getIsTaskInspected() {
return IsTaskInspected;
}
public void setIsTaskInspected(Boolean isTaskInspected) {
IsTaskInspected = isTaskInspected;
}
}
But it is giving class cast exception when I try to cast it to my data object.
Please help me to resolve this?

You are putting in an Array and expecting out a single object. Also, use ArrayList which is serializable.

Not sure what your TasksheetData class is, but maybe you should use your alltasks as a ParcelableArray instead.
Checkout this
Your array of TasksheetData is definitely not an instance of one Serializable class...

Related

Filtering by dot notation and only returning specific results

Customer class
#RealmClass
public class Customer extends RealmObject {
#PrimaryKey private int id;
private int customerSerial;
#Required private String customerName;
private RealmList<Invoice> invoices = new RealmList<>();
public Customer() {}
public Customer(int id, int customerSerial, String customerName) {
this.id = id;
this.customerSerial = customerSerial;
this.customerName = customerName;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public int getCustomerSerial() { return customerSerial; }
public void setCustomerSerial(int customerSerial) { this.customerSerial = customerSerial; }
public String getCustomerName() { return customerName; }
public void setCustomerName(String customerName) { this.customerName = customerName; }
public List<Invoice> getInvoices() { return invoices; }
public void setInvoices(RealmList<Invoice> invoices) { this.invoices = invoices; }
}
Invoice class
#RealmClass
public class Invoice extends RealmObject {
#PrimaryKey private int invoiceNumber;
private Date invoiceDate;
private String invoiceTime;
private int debtorSerNo;
private int deliveryStatus;
private long invoiceSort;
private int driverId;
private String debtorName;
private boolean codCustomer;
private boolean outstandingCOD;
private double outstandingCODAmount;
private String deliveryNotes;
private int lineCount;
public Invoice() {}
public Invoice(TtInvoice invoice) {
this.invoiceNumber = invoice.getInvoiceNumber();
this.invoiceDate = invoice.getInvoiceDate();
this.invoiceTime = invoice.getInvoiceTime();
this.debtorSerNo = invoice.getDebtorSerNo();
this.deliveryStatus = 0;
this.debtorName = invoice.getDebtorName();
this.codCustomer = invoice.isCodCustomer();
this.outstandingCOD = invoice.isOutstandingCOD();
this.outstandingCODAmount = invoice.getOutstandingCODAmount();
this.deliveryNotes = invoice.getDeliveryNotes();
this.lineCount = invoice.getLineCount();
}
public int getInvoiceNumber() {
return invoiceNumber;
}
public void setInvoiceNumber(int invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public LocalDateTime getInvoiceDateTime() {
LocalTime time = LocalTime.parse(invoiceTime);
LocalDate date = invoiceDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return date.atTime(time);
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public String getInvoiceTime() {
return invoiceTime;
}
public void setInvoiceTime(String invoiceTime) {
this.invoiceTime = invoiceTime;
}
public int getDebtorSerNo() {
return debtorSerNo;
}
public void setDebtorSerNo(int debtorSerNo) {
this.debtorSerNo = debtorSerNo;
}
public String getDebtorName() {
return debtorName;
}
public void setDebtorName(String debtorName) {
this.debtorName = debtorName;
}
public boolean isCodCustomer() {
return codCustomer;
}
public void setCodCustomer(boolean codCustomer) {
this.codCustomer = codCustomer;
}
public boolean isOutstandingCOD() {
return outstandingCOD;
}
public void setOutstandingCOD(boolean outstandingCOD) {
this.outstandingCOD = outstandingCOD;
}
public double getOutstandingCODAmount() {
return outstandingCODAmount;
}
public void setOutstandingCODAmount(double outstandingCODAmount) {
this.outstandingCODAmount = outstandingCODAmount;
}
public String getDeliveryNotes() {
return deliveryNotes;
}
public void setDeliveryNotes(String deliveryNotes) {
this.deliveryNotes = deliveryNotes;
}
public int getLineCount() {
return lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
public int getDeliveryStatus() {
return deliveryStatus;
}
public void setDeliveryStatus(int deliveryStatus) {
this.deliveryStatus = deliveryStatus;
}
public long getInvoiceSort() {
return invoiceSort;
}
public void setInvoiceSort(long invoiceSort) {
this.invoiceSort = invoiceSort;
}
public int getDriverId() {
return driverId;
}
public void setDriverId(int driverId) {
this.driverId = driverId;
}
}
TtInvoice class
TtInvoice is created from a remote JSON object when the barcode on an invoice is scanned, have added a constructor just for testing purposes.
public class TtInvoice implements Serializable {
#JsonProperty("Invoice_Number")
private int invoiceNumber;
#JsonProperty("Invoice_Date")
private Date invoiceDate;
#JsonProperty("Invoice_Time")
private String invoiceTime;
#JsonProperty("Debtor_Ser_No")
private int debtorSerNo;
#JsonProperty("Debtor_Name")
private String debtorName;
#JsonProperty("COD_Customer")
private boolean codCustomer;
#JsonProperty("Outstanding_COD")
private boolean outstandingCOD;
#JsonProperty("Outstanding_COD_Amount")
private double outstandingCODAmount;
#JsonProperty("Delivery_Notes")
private String deliveryNotes;
#JsonProperty("Line_Count")
private int lineCount;
public TtInvoice(int invoiceNumber, Date invoiceDate, String invoiceTime, int debtorSerNo, int deliveryStatus) {
this.invoiceNumber = invoiceNumber;
this.invoiceDate = invoiceDate;
this.invoiceTime = invoiceTime;
this.debtorSerNo = debtorSerNo;
this.deliveryStatus = deliveryStatus;
}
public int getInvoiceNumber() {
return invoiceNumber;
}
public void setInvoiceNumber(int invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
public Date getInvoiceDate() {
return invoiceDate;
}
public void setInvoiceDate(Date invoiceDate) {
this.invoiceDate = invoiceDate;
}
public String getInvoiceTime() {
return invoiceTime;
}
public void setInvoiceTime(String invoiceTime) {
this.invoiceTime = invoiceTime;
}
public LocalDateTime getInvoiceDateTime() {
LocalTime time = LocalTime.parse(invoiceTime);
LocalDate date = invoiceDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
return date.atTime(time);
}
public int getDebtorSerNo() {
return debtorSerNo;
}
public void setDebtorSerNo(int debtorSerNo) {
this.debtorSerNo = debtorSerNo;
}
public String getDebtorName() {
return debtorName;
}
public void setDebtorName(String debtorName) {
this.debtorName = debtorName;
}
public String getDeliveryNotes() {
return deliveryNotes;
}
public void setDeliveryNotes(String deliveryNotes) {
this.deliveryNotes = deliveryNotes;
}
public boolean isCodCustomer() {
return codCustomer;
}
public void setCodCustomer(boolean codCustomer) {
this.codCustomer = codCustomer;
}
public boolean isOutstandingCOD() {
return outstandingCOD;
}
public void setOutstandingCOD(boolean outstandingCOD) {
this.outstandingCOD = outstandingCOD;
}
public double getOutstandingCODAmount() {
return outstandingCODAmount;
}
public void setOutstandingCODAmount(double outstandingCODAmount) {
this.outstandingCODAmount = outstandingCODAmount;
}
public int getLineCount() {
return lineCount;
}
public void setLineCount(int lineCount) {
this.lineCount = lineCount;
}
}
In my fragment, if I do
private RealmChangeListener<RealmResults<Customer>> customerRealmChangeListener;
RealmResults<Customer> customerRealmResults;
Realm realm = Realm.getDefaultInstance();
customerRealmChangeListener = customers -> {
customers.forEach(customer -> {
Log.w("CUSTOMERS", customer.getCustomerName());
});
};
customerRealmResults = realm.where(Customer.class).equalTo("invoices.deliveryStatus", 0).findAllAsync();
customerRealmResults.addChangeListener(customerRealmChangeListener);
realm.executeTransactionAsync(transactionRealm -> {
Customer newCustomer = new Customer(1, 1, "Test Customer 1");
Invoice newInvoice1 = new Invoice(new TtInvoice(1234, 20/02/2023, "10:07:00", 1, 0));
Invoice newInvoice2 = new Invoice(new TtInvoice(2468, 20/02/2023, "10:08:00", 1, 1));
newCustomer.getInvoices().add(newInvoice1);
newCustomer.getInvoices().add(newInvoice2);
transactionRealm.insert(newCustomer);
});
No issues with the adding, the problem I am having is the 'findAllAsync', it returns both invoices instead of only the 1.
I get the customer back as I would expect, but a call to 'customer.getInvoices()' returns 2 invoices instead of just 1.
I feel like what I am trying to do is super simple and I'm just not seeing the problem, have been trying to figure this out for a couple of days now to no avail.
If I set a breakpoint on the findAllAsync() call and run my own 'findAll()' using the same query, it has the same issue.
Maybe it is how I am adding new invoices, not 100% sure on that one though.
Otherwise I am liking Realm a hell of a lot better than Room.

How to get JSON Array inside of a JSON Object and iterate

I am trying to communicate with an API using Retrofit in Android Studios but do not know how to get the JSON array within a JSON object.
JSON:
{
"result":{
"status":{
"msg":"success",
"code":200,
"action":2,
"execution_time":"0.505"
},
"page":"1",
"page_size":"40",
"q":"iphone",
"sort":"default",
"tmall":false,
"free_shiping":false,
"total_results":1924963,
"ip":"13.228.169.5",
"item":[
{
"num_iid":619354061232,
"pic":"https://img.alicdn.com/bao/uploaded/i4/2150908574/O1CN01O3Akm82DCwTChbTXg_!!2150908574.jpg",
"title":"Apple/苹果 iPhone XR iphone xs max手机双卡国行原装4G xr苹果x",
"price":"6000",
"promotion_price":"2009",
"sales":1973,
"loc":"广东 深圳",
"seller_id":2150908574,
"seller_nick":"实惠馆超市",
"shop_title":"新魔方数码",
"user_type":0,
"detail_url":"https://item.taobao.com/item.htm?id=619354061232",
"delivery_fee":"0.00"
}
"item":[...]
Method:
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
//not sure what to do here
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
TaobaoModel:
public class TaobaoModel {
#SerializedName("result")
private Result result;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
}
Result:
public class Result {
#SerializedName("status")
private Status status;
#SerializedName("q")
private String q;
#SerializedName("page")
private String page;
#SerializedName("page_size")
private String page_size;
#SerializedName("total_results")
private int total_results;
#SerializedName("tmall")
private String tmall;
#SerializedName("sort")
private String sort;
#SerializedName("free_shiping")
private String free_shiping;
#SerializedName("ip")
private String ip;
#SerializedName("item")
private ArrayList<TaobaoItems> item;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPage_size() {
return page_size;
}
public void setPage_size(String page_size) {
this.page_size = page_size;
}
public int getTotal_results() {
return total_results;
}
public void setTotal_results(int total_results) {
this.total_results = total_results;
}
public String getTmall() {
return tmall;
}
public void setTmall(String tmall) {
this.tmall = tmall;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getFree_shiping() {
return free_shiping;
}
public void setFree_shiping(String free_shiping) {
this.free_shiping = free_shiping;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public ArrayList<TaobaoItems> getItem() {
return item;
}
public void setItem(ArrayList<TaobaoItems> item) {
this.item = item;
}
}
TaobaoItems
public class TaobaoItems {
#SerializedName("num_iid")
private long num_iid;
#SerializedName("pic")
private String pic;
#SerializedName("title")
private String title;
#SerializedName("price")
private String price;
#SerializedName("promotion_price")
private String promotion_price;
#SerializedName("sales")
private int sales;
#SerializedName("loc")
private String loc;
#SerializedName("seller_id")
private long seller_id;
#SerializedName("seller_nick")
private String seller_nick;
#SerializedName("shop_title")
private String shop_title;
#SerializedName("user_type")
private int user_type;
#SerializedName("detail_url")
private String detail_url;
#SerializedName("delivery_fee")
private String delivery_fee;
public TaobaoItems(String title, String price, String pic, String detail_url) {
this.pic = pic;
this.title = title;
this.price = price;
this.detail_url = detail_url;
}
public long getNum_iid() {
return num_iid;
}
public void setNum_iid(long num_iid) {
this.num_iid = num_iid;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPromotion_price() {
return promotion_price;
}
public void setPromotion_price(String promotion_price) {
this.promotion_price = promotion_price;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public long getSeller_id() {
return seller_id;
}
public void setSeller_id(long seller_id) {
this.seller_id = seller_id;
}
public String getSeller_nick() {
return seller_nick;
}
public void setSeller_nick(String seller_nick) {
this.seller_nick = seller_nick;
}
public String getShop_title() {
return shop_title;
}
public void setShop_title(String shop_title) {
this.shop_title = shop_title;
}
public int getUser_type() {
return user_type;
}
public void setUser_type(int user_type) {
this.user_type = user_type;
}
public String getDetail_url() {
return detail_url;
}
public void setDetail_url(String detail_url) {
this.detail_url = detail_url;
}
public String getDelivery_fee() {
return delivery_fee;
}
public void setDelivery_fee(String delivery_fee) {
this.delivery_fee = delivery_fee;
}
}
Status:
public class Status {
#SerializedName("msg")
private String msg;
#SerializedName("code")
private int code;
#SerializedName("action")
private int action;
#SerializedName("execution_time")
private String execution_time;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getAction() {
return action;
}
public void setAction(int action) {
this.action = action;
}
public String getExecution_time() {
return execution_time;
}
public void setExecution_time(String execution_time) {
this.execution_time = execution_time;
}
}
My intention is to get the JSON Array item and display title,price,pic,detail_url from it. I found out how to display it one at a time so far, but couldn't find how to iterate the JSON object so that I can display the data in a listview. Please help, I am new to this and I've been stuck for quite awhile now. If you want to see my interface, retrofit instance etc just let me know.
private void taobaoSearch(){
TaobaoInterface retrofitInterface = RetrofitInstance.getRetrofitInstanceTaobao().create(TaobaoInterface.class);
Call<TaobaoModel> listCall = retrofitInterface.getTaobao("item_search", "40","default", "iphone","taobao-api.p.rapidapi.com", "//apikey hidden");
listCall.enqueue(new Callback<TaobaoModel>() {
#Override
public void onResponse(Call<TaobaoModel> call, Response<TaobaoModel> response) {
List<Result> retro=response.body().getitems();
generateDataList(retro);
}
#Override
public void onFailure(Call<TaobaoModel> call, Throwable t) {
System.out.println("FAILED");
System.out.println(call);
t.printStackTrace();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<Result> dataList) {
recyclerView = findViewById(R.id.customRecycler);
adapter = new CustomAdapter(this,dataList);
recyclerView.setAdapter(adapter);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}

How to parse with Retrofit2 and ArrayList?

I try to parse data but my problem is my json response doesn't start with [].
I use this website( http://www.jsonschema2pojo.org/ ) to help me but it doesn't work without []...
My interface API.java
String BASE_URL = "https://statsapi.web.nhl.com/api/v1/people/";
#Headers("Content-Type: application/json")
#GET("8472382/stats?stats=statsSingleSeason&season=20172018")
Call<Players> getData();
Here's the response I want to parse:
{
"stats":[
{
"type":{
"displayName":"statsSingleSeason"
},
"splits":[
{
"season":"20172018",
"stat":{
"timeOnIce":"1711:02",
"assists":10,
"goals":3,
"pim":21,
"shots":93,
"games":81,
"hits":84,
"powerPlayGoals":0,
"powerPlayPoints":0,
"powerPlayTimeOnIce":"06:17",
"evenTimeOnIce":"1442:16",
"penaltyMinutes":"21",
"faceOffPct":0.0,
"shotPct":3.2,
"gameWinningGoals":0,
"overTimeGoals":0,
"shortHandedGoals":0,
"shortHandedPoints":0,
"shortHandedTimeOnIce":"262:29",
"blocked":188,
"plusMinus":-9,
"points":13,
"shifts":2292,
"timeOnIcePerGame":"21:07",
"evenTimeOnIcePerGame":"17:48",
"shortHandedTimeOnIcePerGame":"03:14",
"powerPlayTimeOnIcePerGame":"00:04"
}
}
]
}
]
}
Try this:
String BASE_URL = "https://statsapi.web.nhl.com/api/v1/people/";
#Headers("Content-Type: application/json")
#GET("8472382.json")
Call<Stats> getData();
These are the models of the JSON posted on stackoverflow, however you should be careful with the Json's URL, because I tried it and It show another json structure.
Create every model in different java files and add public.
class Stats {
private List<Stat> stats;
public List<Stat> getStats() {
return stats;
}
public void setStats(List<Stat> stats) {
this.stats = stats;
}
}
public class Stat {
private StatType type;
private List<Split> splits;
public StatType getType() {
return type;
}
public void setType(StatType type) {
this.type = type;
}
public List<Split> getSplits() {
return splits;
}
public void setSplits(List<Split> splits) {
this.splits = splits;
}
}
class StatType {
private String displayName;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
class Split {
private String season;
StatDetail StatObject;
// Getter Methods
public String getSeason() {
return season;
}
public StatDetail getStat() {
return StatObject;
}
// Setter Methods
public void setSeason(String season) {
this.season = season;
}
public void setStat(StatDetail statObject) {
this.StatObject = statObject;
}
}
class StatDetail {
private String timeOnIce;
private float assists;
private float goals;
private float pim;
private float shots;
private float games;
private float hits;
private float powerPlayGoals;
private float powerPlayPoints;
private String powerPlayTimeOnIce;
private String evenTimeOnIce;
private String penaltyMinutes;
private float faceOffPct;
private float shotPct;
private float gameWinningGoals;
private float overTimeGoals;
private float shortHandedGoals;
private float shortHandedPoints;
private String shortHandedTimeOnIce;
private float blocked;
private float plusMinus;
private float points;
private float shifts;
private String timeOnIcePerGame;
private String evenTimeOnIcePerGame;
private String shortHandedTimeOnIcePerGame;
private String powerPlayTimeOnIcePerGame;
// Getter Methods
public String getTimeOnIce() {
return timeOnIce;
}
public float getAssists() {
return assists;
}
public float getGoals() {
return goals;
}
public float getPim() {
return pim;
}
public float getShots() {
return shots;
}
public float getGames() {
return games;
}
public float getHits() {
return hits;
}
public float getPowerPlayGoals() {
return powerPlayGoals;
}
public float getPowerPlayPoints() {
return powerPlayPoints;
}
public String getPowerPlayTimeOnIce() {
return powerPlayTimeOnIce;
}
public String getEvenTimeOnIce() {
return evenTimeOnIce;
}
public String getPenaltyMinutes() {
return penaltyMinutes;
}
public float getFaceOffPct() {
return faceOffPct;
}
public float getShotPct() {
return shotPct;
}
public float getGameWinningGoals() {
return gameWinningGoals;
}
public float getOverTimeGoals() {
return overTimeGoals;
}
public float getShortHandedGoals() {
return shortHandedGoals;
}
public float getShortHandedPoints() {
return shortHandedPoints;
}
public String getShortHandedTimeOnIce() {
return shortHandedTimeOnIce;
}
public float getBlocked() {
return blocked;
}
public float getPlusMinus() {
return plusMinus;
}
public float getPoints() {
return points;
}
public float getShifts() {
return shifts;
}
public String getTimeOnIcePerGame() {
return timeOnIcePerGame;
}
public String getEvenTimeOnIcePerGame() {
return evenTimeOnIcePerGame;
}
public String getShortHandedTimeOnIcePerGame() {
return shortHandedTimeOnIcePerGame;
}
public String getPowerPlayTimeOnIcePerGame() {
return powerPlayTimeOnIcePerGame;
}
// Setter Methods
public void setTimeOnIce(String timeOnIce) {
this.timeOnIce = timeOnIce;
}
public void setAssists(float assists) {
this.assists = assists;
}
public void setGoals(float goals) {
this.goals = goals;
}
public void setPim(float pim) {
this.pim = pim;
}
public void setShots(float shots) {
this.shots = shots;
}
public void setGames(float games) {
this.games = games;
}
public void setHits(float hits) {
this.hits = hits;
}
public void setPowerPlayGoals(float powerPlayGoals) {
this.powerPlayGoals = powerPlayGoals;
}
public void setPowerPlayPoints(float powerPlayPoints) {
this.powerPlayPoints = powerPlayPoints;
}
public void setPowerPlayTimeOnIce(String powerPlayTimeOnIce) {
this.powerPlayTimeOnIce = powerPlayTimeOnIce;
}
public void setEvenTimeOnIce(String evenTimeOnIce) {
this.evenTimeOnIce = evenTimeOnIce;
}
public void setPenaltyMinutes(String penaltyMinutes) {
this.penaltyMinutes = penaltyMinutes;
}
public void setFaceOffPct(float faceOffPct) {
this.faceOffPct = faceOffPct;
}
public void setShotPct(float shotPct) {
this.shotPct = shotPct;
}
public void setGameWinningGoals(float gameWinningGoals) {
this.gameWinningGoals = gameWinningGoals;
}
public void setOverTimeGoals(float overTimeGoals) {
this.overTimeGoals = overTimeGoals;
}
public void setShortHandedGoals(float shortHandedGoals) {
this.shortHandedGoals = shortHandedGoals;
}
public void setShortHandedPoints(float shortHandedPoints) {
this.shortHandedPoints = shortHandedPoints;
}
public void setShortHandedTimeOnIce(String shortHandedTimeOnIce) {
this.shortHandedTimeOnIce = shortHandedTimeOnIce;
}
public void setBlocked(float blocked) {
this.blocked = blocked;
}
public void setPlusMinus(float plusMinus) {
this.plusMinus = plusMinus;
}
public void setPoints(float points) {
this.points = points;
}
public void setShifts(float shifts) {
this.shifts = shifts;
}
public void setTimeOnIcePerGame(String timeOnIcePerGame) {
this.timeOnIcePerGame = timeOnIcePerGame;
}
public void setEvenTimeOnIcePerGame(String evenTimeOnIcePerGame) {
this.evenTimeOnIcePerGame = evenTimeOnIcePerGame;
}
public void setShortHandedTimeOnIcePerGame(String shortHandedTimeOnIcePerGame) {
this.shortHandedTimeOnIcePerGame = shortHandedTimeOnIcePerGame;
}
public void setPowerPlayTimeOnIcePerGame(String powerPlayTimeOnIcePerGame) {
this.powerPlayTimeOnIcePerGame = powerPlayTimeOnIcePerGame;
}
}

Realm in android

I want to use two class for database.
here is my source.
public class UserInfo extends RealmObject {
private String user_email;
private String nick_name;
private String expected_date;
private boolean initial_autho;
private int resultDay;
public int getResultDay() {
return resultDay;
}
public void setResultDay(int resultDay) {
this.resultDay = resultDay;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getNick_name() {
return nick_name;
}
public void setNick_name(String nick_name) {
this.nick_name = nick_name;
}
public String getExpected_date() {
return expected_date;
}
public void setExpected_date(String expected_date) {
this.expected_date = expected_date;
}
public boolean getInitial_autho() {
return initial_autho;
}
public void setInitial_autho(boolean initial_autho) {
this.initial_autho = initial_autho;
}
}
public class Calendar extends Realmobject {
private long millis;
private String note; // 노트
private String mail; // who
private int image; // image resource
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public long getTime() {
return millis;
}
public String getNote() {
return note;
}
public int getImage() {
return image;
}
public void setDate(long time) {
this.millis = time;
}
public void setNote(String note) {
this.note = note;
}
public void setImage(int image) {
this.image = image;
}
}
How do I use these things in Activity?
I don't know exactly and I much appreciate if you guys could tell about that more specifically as much as you can.

Not able to access getter method of POJO inside OnNext() in rxretrofit

I am trying to access getter property of the pojo received in the response, but there is no such option.so is there any other way, I can do that?
The code for that call is as below:
results.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<GenericResponse<List<FoodTruck>>>() {
#Override
public void onCompleted() {
Toast.makeText(getActivity(), "completed", Toast.LENGTH_SHORT).show();
unsubscribe();
}
#Override
public void onError(Throwable e) {
Toast.makeText(getActivity(), "error", Toast.LENGTH_SHORT).show();
}
#Override
public void onNext(GenericResponse<List<FoodTruck>> response) {
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
}
});
GenericResponse.java
public class GenericResponse<T> {
#JsonProperty("status")
private String status;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private T data;
}
FoodTruck.java
#JsonInclude(JsonInclude.Include.NON_NULL)
public class FoodTruck implements Parcelable {
#JsonProperty("_id")
private String foodTruckId;
#JsonProperty("foodtruck_name")
private String foodTruckName;
#JsonProperty("foodtruck_location")
private String foodTruckLocation;
#JsonProperty("foodtruck_tag")
private String foodTruckTag;
#JsonProperty("foodtruck_timing")
private String foodTruckTiming;
#JsonProperty("foodtruck_cusine")
private String foodTruckCusine;
#JsonProperty("foodtruck_img")
private String foodTruckImg;
#JsonProperty("foodtruck_logo")
private String foodTruckLogo;
#JsonProperty("foodtruck_total_votes")
private int foodTruckTotalVotes;
#JsonProperty("foodtruck_rating")
private double foodTruckRating;
#JsonProperty("item_list")
private List<FoodTruckItem> foodTruckItemList;
public String getFoodTruckId() {
return foodTruckId;
}
public String getFoodTruckName() {
return foodTruckName;
}
public String getFoodTruckLocation() {
return foodTruckLocation;
}
public String getFoodTruckTag() {
return foodTruckTag;
}
public String getFoodTruckTiming() {
return foodTruckTiming;
}
public String getFoodTruckCusine() {
return foodTruckCusine;
}
public String getFoodTruckImg() {
return foodTruckImg;
}
public String getFoodTruckLogo() {
return foodTruckLogo;
}
public int getFoodTruckTotalVotes() {
return foodTruckTotalVotes;
}
public double getFoodTruckRating() {
return foodTruckRating;
}
public List<FoodTruckItem> getFoodTruckItemList() {
return foodTruckItemList;
}
public void setFoodTruckId(String foodTruckId) {
this.foodTruckId = foodTruckId;
}
public void setFoodTruckName(String foodTruckName) {
this.foodTruckName = foodTruckName;
}
public void setFoodTruckLocation(String foodTruckLocation) {
this.foodTruckLocation = foodTruckLocation;
}
public void setFoodTruckTag(String foodTruckTag) {
this.foodTruckTag = foodTruckTag;
}
public void setFoodTruckTiming(String foodTruckTiming) {
this.foodTruckTiming = foodTruckTiming;
}
public void setFoodTruckCusine(String foodTruckCusine) {
this.foodTruckCusine = foodTruckCusine;
}
public void setFoodTruckImg(String foodTruckImg) {
this.foodTruckImg = foodTruckImg;
}
public void setFoodTruckLogo(String foodTruckLogo) {
this.foodTruckLogo = foodTruckLogo;
}
public void setFoodTruckTotalVotes(int foodTruckTotalVotes) {
this.foodTruckTotalVotes = foodTruckTotalVotes;
}
public void setFoodTruckRating(double foodTruckRating) {
this.foodTruckRating = foodTruckRating;
}
public void setFoodTruckItemList(List<FoodTruckItem> foodTruckItemList) {
this.foodTruckItemList = foodTruckItemList;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.foodTruckId);
dest.writeString(this.foodTruckName);
dest.writeString(this.foodTruckLocation);
dest.writeString(this.foodTruckTag);
dest.writeString(this.foodTruckTiming);
dest.writeString(this.foodTruckCusine);
dest.writeString(this.foodTruckImg);
dest.writeString(this.foodTruckLogo);
dest.writeInt(this.foodTruckTotalVotes);
dest.writeDouble(this.foodTruckRating);
dest.writeTypedList(this.foodTruckItemList);
}
public FoodTruck() {
}
protected FoodTruck(Parcel in) {
this.foodTruckId = in.readString();
this.foodTruckName = in.readString();
this.foodTruckLocation = in.readString();
this.foodTruckTag = in.readString();
this.foodTruckTiming = in.readString();
this.foodTruckCusine = in.readString();
this.foodTruckImg = in.readString();
this.foodTruckLogo = in.readString();
this.foodTruckTotalVotes = in.readInt();
this.foodTruckRating = in.readDouble();
this.foodTruckItemList = in.createTypedArrayList(FoodTruckItem.CREATOR);
}
public static final Parcelable.Creator<FoodTruck> CREATOR = new Parcelable.Creator<FoodTruck>() {
#Override
public FoodTruck createFromParcel(Parcel source) {
return new FoodTruck(source);
}
#Override
public FoodTruck[] newArray(int size) {
return new FoodTruck[size];
}
};
}
FoodTruckItem.java
#JsonInclude(JsonInclude.Include.NON_NULL)
public class FoodTruckItem implements Parcelable {
#JsonProperty("_id")
private String itemId;
#JsonProperty("no_of_times_ordered")
private int noOfTimesOrdered;
#JsonProperty("item_name")
private String itemName;
#JsonProperty("item_tag")
private String itemTag;
#JsonProperty("item_category")
private String itemCategory;
#JsonProperty("item_stock")
private int itemStock;
#JsonProperty("item_price")
private double itemPrice;
#JsonProperty("item_img")
private String itemImg;
#JsonProperty("no_of_likes")
private int noOfLikes;
#JsonProperty("item_quantity_ordered")
private int itemQuantityOrdered;
#JsonProperty("item_illustrations")
private List<String> itemIllustration;
public String getItemId() {
return itemId;
}
public int getNoOfTimesOrdered() {
return noOfTimesOrdered;
}
public String getItemName() {
return itemName;
}
public String getItemTag() {
return itemTag;
}
public String getItemCategory() {
return itemCategory;
}
public int getItemStock() {
return itemStock;
}
public double getItemPrice() {
return itemPrice;
}
public String getItemImg() {
return itemImg;
}
public int getNoOfLikes() {
return noOfLikes;
}
public int getItemQuantityOrdered() {
return itemQuantityOrdered;
}
public List<String> getItemIllustration() {
return itemIllustration;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public void setNoOfTimesOrdered(int noOfTimesOrdered) {
this.noOfTimesOrdered = noOfTimesOrdered;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public void setItemTag(String itemTag) {
this.itemTag = itemTag;
}
public void setItemCategory(String itemCategory) {
this.itemCategory = itemCategory;
}
public void setItemStock(int itemStock) {
this.itemStock = itemStock;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
public void setItemImg(String itemImg) {
this.itemImg = itemImg;
}
public void setNoOfLikes(int noOfLikes) {
this.noOfLikes = noOfLikes;
}
public void setItemQuantityOrdered(int itemQuantityOrdered) {
this.itemQuantityOrdered = itemQuantityOrdered;
}
public void setItemIllustration(List<String> itemIllustration) {
this.itemIllustration = itemIllustration;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.itemId);
dest.writeInt(this.noOfTimesOrdered);
dest.writeString(this.itemName);
dest.writeString(this.itemTag);
dest.writeString(this.itemCategory);
dest.writeInt(this.itemStock);
dest.writeDouble(this.itemPrice);
dest.writeString(this.itemImg);
dest.writeInt(this.noOfLikes);
dest.writeInt(this.itemQuantityOrdered);
dest.writeStringList(this.itemIllustration);
}
public FoodTruckItem() {
}
protected FoodTruckItem(Parcel in) {
this.itemId = in.readString();
this.noOfTimesOrdered = in.readInt();
this.itemName = in.readString();
this.itemTag = in.readString();
this.itemCategory = in.readString();
this.itemStock = in.readInt();
this.itemPrice = in.readDouble();
this.itemImg = in.readString();
this.noOfLikes = in.readInt();
this.itemQuantityOrdered = in.readInt();
this.itemIllustration = in.createStringArrayList();
}
public static final Parcelable.Creator<FoodTruckItem> CREATOR = new Parcelable.Creator<FoodTruckItem>() {
#Override
public FoodTruckItem createFromParcel(Parcel source) {
return new FoodTruckItem(source);
}
#Override
public FoodTruckItem[] newArray(int size) {
return new FoodTruckItem[size];
}
};
}
Now Basically I want to acess someting like response.getData().... But there is no such option.
Possibly data not accessible, because it is private. Try to crete getter method.
public class GenericResponse<T> {
#JsonProperty("status")
private String status;
#JsonProperty("message")
private String message;
#JsonProperty("data")
private T data;
public T getData() {
return data;
}
}

Categories

Resources