Multiple check item send params - android

I have set switch box in adapter when switch box is enable then open custom check box list item. I have select check box item multiple. This switch box design when select spinner item and then open fragment page. When select multiple check box item and send JSON param like this:
"attendees": [
{
"id": "1",
"person": "xza"
},
{
"id": "2",
"person": "cfd"
}
]
And send button applying in activity. Spinner and save button design in activity and select item design in fragment.
I have make model class like:
public class MeetingModel {
public String date;
public String time;
public boolean reminder;
public boolean assignTOther;
public boolean contactTo;
public boolean attendeesTo;
public String remark;
private MeetingReminder meetingReminder;
private int assignid;
private int contactid;
private List<Assigne> attendees = null;
private int attendeesid;
private String location;
private String purpose;
private String clientType;
private String id;
private String logSubType;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public boolean isReminder() {
return reminder;
}
public void setReminder(boolean reminder) {
this.reminder = reminder;
}
public boolean isAssignTOther() {
return assignTOther;
}
public void setAssignTOther(boolean assignTOther) {
this.assignTOther = assignTOther;
}
public boolean isContactTo() {
return contactTo;
}
public void setContactTo(boolean contactTo) {
this.contactTo = contactTo;
}
public boolean isAttendeesTo() {
return attendeesTo;
}
public void setAttendeesTo(boolean attendeesTo) {
this.attendeesTo = attendeesTo;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public MeetingReminder getMeetingReminder() {
return meetingReminder;
}
public void setMeetingReminder(MeetingReminder meetingReminder) {
this.meetingReminder = meetingReminder;
}
public int getAssignid() {
return assignid;
}
public void setAssignid(int assignid) {
this.assignid = assignid;
}
public int getContactid() {
return contactid;
}
public void setContactid(int contactid) {
this.contactid = contactid;
}
public void setMeetingReminder(String date, String time) {
MeetingReminder meetingReminder = new MeetingReminder();
meetingReminder.setDate(date);
meetingReminder.setTime(time);
setMeetingReminder(meetingReminder);
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public String getClientType() {
return clientType;
}
public void setClientType(String clientType) {
this.clientType = clientType;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLogSubType() {
return logSubType;
}
public void setLogSubType(String logSubType) {
this.logSubType = logSubType;
}
public List<Assigne> getAttendees() {
return attendees;
}
public void setAttendees(List<Assigne> attendees) {
this.attendees = attendees;
}
public JsonArray getCheckedItems(){
List<Assigne> tmpList=new ArrayList<>();
List<Assigne> attendees = new ArrayList<>();
JsonArray jsonArray = new JsonArray();
for(Assigne attendee:attendees){
if(attendee.isHeaderSelected()){
tmpList.add(attendee);
attendee.setHeaderSelected(true);
JsonObject obj = new JsonObject();
obj.addProperty("id", attendee.getId());
obj.addProperty("name", attendee.getName());
jsonArray.add(obj);
}
}
return jsonArray;
}
}
I expect the output is:
"attendees":[{"id":"1","person":"fff"},{"id":"2","person":"dfdf"}]
But the actual output is:
"attendees": []

Related

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

RecyclerView to Firebase database

I actually want cardView in my RecyclerView to retrieve data from firebase but it returns error. Please do help me to attach my RecyclerView to firebase and retrieve data from it.
Thanking you in advance.
Here is the mainActivity.java
mbloglist = findViewById(R.id.rv1);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
productAdapter adapter = new productAdapter(this);
mbloglist.setLayoutManager(layoutManager);
mbloglist.setAdapter(adapter);
Toast.makeText(getApplicationContext(),"Layout starting",Toast.LENGTH_SHORT).show();
database1 = FirebaseDatabase.getInstance();
myRef = database1.getReference("Users");
Toast.makeText(getApplicationContext(),"Database Done",Toast.LENGTH_SHORT).show();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e("pppp","onDataChange"+dataSnapshot.toString());
Toast.makeText(getApplicationContext(),"Done",Toast.LENGTH_SHORT).show();
for(DataSnapshot child : dataSnapshot.getChildren()){
ModelClass modelClass = child.getValue(ModelClass.class);
modelClassList.add(modelClass);
}
Toast.makeText(getApplicationContext(),"Done Done",Toast.LENGTH_SHORT).show();
adapter.addItems(modelClassList);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("pppp","onCancelled");
}
});
}
Here is the Adapter which named ProductAdapter.java
public productAdapter(Context context) {
this.context = context;
this.productList = new ArrayList<>();
}
public void addItems(List<ModelClass> productList){
this.productList = productList;
this.notifyDataSetChanged();
}
#NonNull
#Override
public productViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new productViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent,false));
}
#Override
public void onBindViewHolder(#NonNull productViewHolder holder, int position) {
ModelClass modelClass = productList.get(position);
holder.shop_name.setText(modelClass.getStore_name());
holder.phone_number.setText(modelClass.getphone_number());
holder.v7b.setText(modelClass.getV7b());
holder.v7g.setText(modelClass.getV7g());
holder.y53b.setText(modelClass.getY53b());
holder.y53g.setText(modelClass.getY53g());
holder.v7pb.setText(modelClass.getV7pb());
holder.v7pg.setText(modelClass.getV7pg());
holder.y55sb.setText(modelClass.getY55sb());
holder.y55sg.setText(modelClass.getY55sb());
holder.i3b.setText(modelClass.getI3b());
holder.i3go.setText(modelClass.getI3go());
holder.i3gr.setText(modelClass.getI3gr());
holder.i3prob.setText(modelClass.getI3prob());
holder.i3progo.setText(modelClass.getI3progo());
holder.i3progr.setText(modelClass.getI3progr());
holder.i5b.setText(modelClass.getI5b());
holder.i5go.setText(modelClass.getI5go());
holder.i5gr.setText(modelClass.getI5gr());
holder.i5prob.setText(modelClass.getI5prob());
holder.i5progo.setText(modelClass.getI5progo());
holder.i5progr.setText(modelClass.getI5progr());
holder.i7b.setText(modelClass.getI7b());
holder.i7go.setText(modelClass.getI7go());
holder.i7gr.setText(modelClass.getI7gr());
holder.camonb.setText(modelClass.getCamonb());
holder.camongo.setText(modelClass.getCamongo());
holder.camonbl.setText(modelClass.getCamonbl());
}
#Override
public int getItemCount() {
return 0;
}
class productViewHolder extends RecyclerView.ViewHolder{
private TextView shop_name,phone_number,v7b,v7g,y53b,y53g,v7pb,v7pg,y55sb,y55sg,y69b,y69g,i3b,i3go,i3gr,i3prob,i3progo,i3progr,i5b,i5go,i5gr,i5prob,i5progo,i5progr,i7b,i7go,i7gr,camonb,camongo,camonbl;
public productViewHolder(View itemView){
super(itemView);
shop_name = itemView.findViewById(R.id.EditText2000);
phone_number=itemView.findViewById(R.id.EditText2001);
v7b=itemView.findViewById(R.id.EditText101);
v7g=itemView.findViewById(R.id.EditText102);
y53b=itemView.findViewById(R.id.EditText103);
y53g=itemView.findViewById(R.id.EditText104);
v7pb=itemView.findViewById(R.id.EditText105);
v7pg=itemView.findViewById(R.id.EditText106);
y55sb=itemView.findViewById(R.id.EditText107);
y55sg=itemView.findViewById(R.id.EditText108);
y69b=itemView.findViewById(R.id.EditText109);
y69g=itemView.findViewById(R.id.EditText110);
i3b=itemView.findViewById(R.id.EditText111);
i3go=itemView.findViewById(R.id.EditText112);
i3gr=itemView.findViewById(R.id.EditText113);
i3prob=itemView.findViewById(R.id.EditText114);
i3progo=itemView.findViewById(R.id.EditText115);
i3progr=itemView.findViewById(R.id.EditText116);
i5b=itemView.findViewById(R.id.EditText117);
i5go=itemView.findViewById(R.id.EditText118);
i5gr=itemView.findViewById(R.id.EditText119);
i5prob=itemView.findViewById(R.id.EditText120);
i5progo=itemView.findViewById(R.id.EditText121);
i5progr=itemView.findViewById(R.id.EditText122);
i7b=itemView.findViewById(R.id.EditText123);
i7go=itemView.findViewById(R.id.EditText124);
i7gr=itemView.findViewById(R.id.EditText125);
camonb=itemView.findViewById(R.id.EditText126);
camongo=itemView.findViewById(R.id.EditText127);
camonbl=itemView.findViewById(R.id.EditText128);
Here is the modelclass.java which attached to firebase
public class ModelClass {
String v7b;
String v7g;
String y53b;
String y53g;
String v7pb;
String v7pg;
String y55sb;
String y55sg;
String y69b;
String y69g;
String i3b;
String i3go;
String i3gr;
String i3prob;
String i3progo;
String i3progr;
String i5b;
String i5go;
String i5gr;
String i5prob;
String i5progo;
String i5progr;
String i7b;
String i7go;
String i7gr;
String camonb;
String camongo;
String camonbl;
String email;
String store_name;
String phone_number;
public ModelClass() {
}
public ModelClass(String v7b, String v7g, String y53b, String y53g, String v7pb, String v7pg, String y55sb, String y55sg, String y69b, String y69g, String i3b, String i3go, String i3gr, String i3prob, String i3progo, String i3progr, String i5b, String i5go, String i5gr, String i5prob, String i5progo, String i5progr, String i7b, String i7go, String i7gr, String camonb, String camongo, String camongr) {
this.v7b = v7b;
this.v7g = v7g;
this.y53b = y53b;
this.y53g = y53g;
this.v7pb = v7pb;
this.v7pg = v7pg;
this.y55sb = y55sb;
this.y55sg = y55sg;
this.y69b = y69b;
this.y69g = y69g;
this.i3b = i3b;
this.i3go = i3go;
this.i3gr = i3gr;
this.i3prob = i3prob;
this.i3progo = i3progo;
this.i3progr = i3progr;
this.i5b = i5b;
this.i5go = i5go;
this.i5gr = i5gr;
this.i5prob = i5prob;
this.i5progo = i5progo;
this.i5progr = i5progr;
this.i7b = i7b;
this.i7go = i7go;
this.i7gr = i7gr;
this.camonb = camonb;
this.camongo = camongo;
this.camonbl = camongr;
}
public ModelClass(String email, String store_name, String phone_number) {
this.email = email;
this.store_name = store_name;
this.phone_number = phone_number;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPhone() {
return phone;
}
String phone;
public String getV7b() {
return v7b;
}
public void setV7b(String v7b) {
this.v7b = v7b;
}
public String getV7g() {
return v7g;
}
public void setV7g(String v7g) {
this.v7g = v7g;
}
public String getY53b() {
return y53b;
}
public void setY53b(String y53b) {this.y53b = y53b;}
public String getY53g() {
return y53g;
}
public void setY53g(String y53g) {
this.y53g = y53g;
}
public String getV7pb() {
return v7pb;
}
public void setV7pb(String v7pb) {
this.v7pb = v7pb;
}
public String getV7pg() {
return v7pg;
}
public void setV7pg(String v7pg) {
this.v7pg = v7pg;
}
public String getY55sb() {
return y55sb;
}
public void setY55sb(String y55sb) {
this.y55sb = y55sb;
}
public String getY55sg() {
return y55sg;
}
public void setY55sg(String y55sg) {
this.y55sg = y55sg;
}
public String getY69b() {
return y69b;
}
public void setY69b(String y69b) {
this.y69b = y69b;
}
public String getY69g() {
return y69g;
}
public void setY69g(String y69g) {
this.y69g = y69g;
}
public String getI3b() {
return i3b;
}
public void setI3b(String i3b) {
this.i3b = i3b;
}
public String getI3go() {
return i3go;
}
public void setI3go(String i3go) {
this.i3go = i3go;
}
public String getI3gr() {
return i3gr;
}
public void setI3gr(String i3gr) {
this.i3gr = i3gr;
}
public String getI3prob() {
return i3prob;
}
public void setI3prob(String i3prob) {
this.i3prob = i3prob;
}
public String getI3progo() {
return i3progo;
}
public void setI3progo(String i3progo) {
this.i3progo = i3progo;
}
public String getI3progr() {
return i3progr;
}
public void setI3progr(String i3progr) {
this.i3progr = i3progr;
}
public String getI5b() {
return i5b;
}
public void setI5b(String i5b) {
this.i5b = i5b;
}
public String getI5go() {
return i5go;
}
public void setI5go(String i5go) {
this.i5go = i5go;
}
public String getI5gr() {
return i5gr;
}
public void setI5gr(String i5gr) {
this.i5gr = i5gr;
}
public String getI5prob() {
return i5prob;
}
public void setI5prob(String i5prob) {
this.i5prob = i5prob;
}
public String getI5progo() {
return i5progo;
}
public void setI5progo(String i5progo) {
this.i5progo = i5progo;
}
public String getI5progr() {
return i5progr;
}
public void setI5progr(String i5progr) {
this.i5progr = i5progr;
}
public String getI7b() {
return i7b;
}
public void setI7b(String i7b) {
this.i7b = i7b;
}
public String getI7go() {
return i7go;
}
public void setI7go(String i7go) {
this.i7go = i7go;
}
public String getI7gr() {
return i7gr;
}
public void setI7gr(String i7gr) {
this.i7gr = i7gr;
}
public String getCamonb() {
return camonb;
}
public void setCamonb(String camonb) {
this.camonb = camonb;
}
public String getCamongo() {
return camongo;
}
public void setCamongo(String camongo) {
this.camongo = camongo;
}
public String getCamonbl() {
return camonbl;
}
public void setCamongr(String camongr) {
this.camonbl = camongr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStore_name() {
return store_name;
}
public void setStorename(String storename) {this.store_name = storename;}
public String getphone_number() {
return phone_number;
}
public void setphone_number(String phone_number) {
this.phone_number = phone_number;
}
}
Here is the Firebase Realtime Database Image
ModelClass class and your database doesn't have the same structure, because in your database you have a new node called "phone" inside each userID node.
You can try 3 approaches to solve this issue:
a.) Write data in your database just like ModelClass is, without "phone" node.
b.) Create a new class called "Phone" with same attributes you have inside "phone" node in the database, and make this new class part of ModelClass class.
c.) On myRef onDataChange method, inside for statement, check for each child key and fill ModelClass atributes one by one. When the child key is equal to "phone", start a new loop statement in "phone" children to fill these attributes.
Add the following code:
#Override
public int getItemCount() {
return productList.size();
}

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.

Save ArrayList<pojo> in SharedPreferences

I am using tabs which consist of fragment that has an arraylist of objects. I want to store my arraylist
list<Model_BarcodeDetail>
onStop() ie., I want to store my list that is present in my current tab when I navigate to another tab. I did the following code but it is giving me exception when I'm trying to save my list.
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("=====pause");
saveDatas();
}
public void saveDatas() {
Log.d("msg", "Save Instance");
SharedPreferences.Editor outState = getActivity().getSharedPreferences(
"order", Context.MODE_APPEND).edit();
text = editText_barcode.getText().toString();
itemQuantity = editText_quantity.getText().toString();
outState.putString("saved", "true");
outState.putString("text", text);
outState.putString("title", job_name);
outState.putString("area", selected_area);
outState.putString("location", selected_loc);
outState.putString("quantity", itemQuantity);
//String strObject = gson.toJson(list, Model_BarcodeDetail.class);
//outState.putString("MyList", strObject);
POJO mPojo = new POJO();
mPojo.setData(list);
String strObject = gson.toJson(mPojo, POJO.class);
outState.putString("MyList", strObject);
outState.commit();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Bundle extras = getArguments();
/***** PUT DATA IN EDITTEXT if ITS AVAILABLE IN BUNDLE *****/
System.out.println("===jobname:"+job_name);
SharedPreferences orderData = getActivity().getSharedPreferences(
"order", Context.MODE_APPEND);
if (orderData != null) {
String a = orderData.getString("saved", "");
if (a != null && a.equalsIgnoreCase("true")) {
text = orderData.getString("text", "");
System.out.println("====tetx:" + text);
String title = orderData.getString("title", "");
System.out.println("===title: "+title+"===jobname: "+job_name);
if (title.equalsIgnoreCase(job_name)) {
editText_barcode.setText(text);
selected_area = orderData.getString("area", "");
selected_loc = orderData.getString("location", "");
itemQuantity = orderData.getString("quantity", "");
editText_quantity.setText(itemQuantity);
String json = orderData.getString("MyList", "");
List<Model_BarcodeDetail> list = gson.fromJson(json,
listOfObjects);
}
}
}
}
I'm getting the following exception when I add another tab:
12-09 12:08:28.072: E/AndroidRuntime(28616): FATAL EXCEPTION: main
12-09 12:08:28.072: E/AndroidRuntime(28616): Process: com.example.pdt, PID:
28616
12-09 12:08:28.072: E/AndroidRuntime(28616): java.lang.NullPointerException
12-09 12:08:28.072: E/AndroidRuntime(28616): at
com.example.pdt.Fragment_Main.saveDatas(Fragment_Main.java:446)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
com.example.pdt.Fragment_Main.onPause(Fragment_Main.java:426)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.Fragment.performPause(Fragment.java:1950)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1005)
12-09 12:08:28.072: E/AndroidRuntime(28616): at
android.support.v4.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1235)
EDIT:
Model_BarcodeDetail class:
package com.example.model;
public class Model_BarcodeDetail {
public String datetime, success, name, reference, description, price,
color, size, stock, branch, supplier, location, basesell, vat,
avg_cost, last_cost, next_cost, group_code, type, remarks1,
remarks2, listed_days, title, meta_keywords, meta_description,
job_id, total, fixedTotal, fixedPrice, aliascode, draftName,
itemBarcode, totalDiscount;
boolean priceEdited;
public boolean isPriceEdited() {
return priceEdited;
}
public void setPriceEdited(boolean priceEdited) {
this.priceEdited = priceEdited;
}
private String string_sale_return;
public String barcode, quantity = "0", area, batch;
private boolean scanned, isEdited;
public String getTotalDiscount() {
return totalDiscount;
}
public void setTotalDiscount(String totalDiscount) {
this.totalDiscount = totalDiscount;
}
public String getItemBarcode() {
return itemBarcode;
}
public void setItemBarcode(String itemBarcode) {
this.itemBarcode = itemBarcode;
}
public String getDraftName() {
return draftName;
}
public void setDraftName(String draftName) {
this.draftName = draftName;
}
public String getAliascode() {
return aliascode;
}
public void setAliascode(String aliascode) {
this.aliascode = aliascode;
}
public String getString_sale_return() {
return string_sale_return;
}
public void setString_sale_return(String string_sale_return) {
this.string_sale_return = string_sale_return;
}
public boolean isScanned() {
return scanned;
}
public void setScanned(boolean scanned) {
this.scanned = scanned;
}
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getStock() {
return stock;
}
public void setStock(String stock) {
this.stock = stock;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBasesell() {
return basesell;
}
public void setBasesell(String basesell) {
this.basesell = basesell;
}
public String getVat() {
return vat;
}
public void setVat(String vat) {
this.vat = vat;
}
public String getAvg_cost() {
return avg_cost;
}
public void setAvg_cost(String avg_cost) {
this.avg_cost = avg_cost;
}
public String getLast_cost() {
return last_cost;
}
public void setLast_cost(String last_cost) {
this.last_cost = last_cost;
}
public String getNext_cost() {
return next_cost;
}
public void setNext_cost(String next_cost) {
this.next_cost = next_cost;
}
public String getGroup_code() {
return group_code;
}
public void setGroup_code(String group_code) {
this.group_code = group_code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getRemarks1() {
return remarks1;
}
public void setRemarks1(String remarks1) {
this.remarks1 = remarks1;
}
public String getRemarks2() {
return remarks2;
}
public void setRemarks2(String remarks2) {
this.remarks2 = remarks2;
}
public String getListed_days() {
return listed_days;
}
public void setListed_days(String listed_days) {
this.listed_days = listed_days;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMeta_keywords() {
return meta_keywords;
}
public void setMeta_keywords(String meta_keywords) {
this.meta_keywords = meta_keywords;
}
public String getMeta_description() {
return meta_description;
}
public void setMeta_description(String meta_description) {
this.meta_description = meta_description;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public boolean isEdited() {
return isEdited;
}
public void setEdited(boolean isEdited) {
this.isEdited = isEdited;
}
public String getFixedTotal() {
return fixedTotal;
}
public void setFixedTotal(String fixedTotal) {
this.fixedTotal = fixedTotal;
}
public String getFixedPrice() {
return fixedPrice;
}
public void setFixedPrice(String fixedPrice) {
this.fixedPrice = fixedPrice;
}
}
POJO class:
package com.example.model;
import java.util.List;
public class Pojo {
List<Model_BarcodeDetail> data;
public List<Model_BarcodeDetail> getData() {
return data;
}
public void setData(List<Model_BarcodeDetail> data) {
this.data = data;
}
}
You need to store your list in the model class like this
public class POJO {
List<Model_BarcodeDetail> data;
public List<Model_BarcodeDetail> getData() {
return data;
}
public void setData(List<Model_BarcodeDetail> data) {
this.data = data;
}
}
now when you have data in your POJO class
Convert it to json string and store to prefrence like this
String strObject = gson.toJson(list, POJO.class);
outState.putString("MyList", strObject);
Now when you want to get back those data just do like this
String json = orderData.getString("MyList", "");
POJO mPojo = gson.fromJson(json,POJO.class);
now access you List using this object like this
mPojo.getModel_BarcodeList();
Let me know if you still have an issue
You can use TinyDB -- Android-Shared-Preferences-Turbo

Android Realm return exception "Table has no columns"

This is my code:
PSTrip psTrip = JsonUtil.jsonToObject(jsonObject.toString(), PSTrip.class);
int size = psTrip.getTripSteps().size()-1;
RealmList<Step> steps = psTrip.getTripSteps().get(size).getSteps();
RealmList<TripStep> tripSteps = psTrip.getTripSteps();
Log.i("","continue init after getting tripsteps and steps");
if(tripSteps.size() > 0) {
Log.i("","continue init blabla");
for (int i = 0; i < tripSteps.size(); i++) {
RealmList<Step> mergedSteps = Utils.getMergedSteps(context, tripSteps.get(i).getRoute().getSteps());
tripSteps.get(i).getRoute().getSteps().clear();
for (Step step : mergedSteps) {
tripSteps.get(i).getRoute().getSteps().add(step);
}
}
Log.i("", "continue init after for in which I merge the steps for the tripsteps");
steps = Utils.getMergedSteps(context, steps);
Log.i("", "continue init after merging the steps");
tripSteps.get(size).setSteps(steps);
Log.i("", "continue init after settting steps on tripsteps");
psTrip.setTripSteps(tripSteps);
}
PSTripDBFactory.getInstance(context).addToList(psTrip);
The Utils.getMergedSteps just takes the list of steps (Step from Google maps class), and if it is possible, it merges them.
My problem is at the last line which does:
public void addToList(PSTrip psTrip){
try{
PSTrip insideAlready = getListOfCompletedTripsByID(psTrip.getId());
Log.i("","continue init inside already:" + insideAlready);
if(insideAlready == null){
Log.i("","continue init will copy to realm");
realm.beginTransaction();
realm.copyToRealm(psTrip);
realm.commitTransaction();
Log.i("","continue init will copy to realm finished");
}else{
Log.i("","continue init will copyorupdate to realm");
realm.beginTransaction();
realm.copyToRealmOrUpdate(psTrip);
realm.commitTransaction();
Log.i("","continue init will copyorupdate to realm finished");
}
}catch (Exception e){
Log.i("","continue init error trying to add to realm" + e.getMessage());
realm.cancelTransaction();
}
}
Where getListOfCompletedTripsByID is the following function:
public PSTrip getListOfCompletedTripsByID( String id){
RealmResults<PSTrip> completed = realm.where(PSTrip.class).equalTo("id" , id).findAll();
if(completed.size() > 0){
return completed.get(0);
}else{
return null;
}
}
I get back the following error response:
03-18 11:14:56.135 21908-21908/nl.hgrams.passenger I/﹕ continue init after for in which I merge the steps for the tripsteps
03-18 11:14:56.135 21908-21908/nl.hgrams.passenger I/﹕ continue init after merging the steps
03-18 11:14:56.135 21908-21908/nl.hgrams.passenger I/﹕ continue init after settting steps on tripsteps
03-18 11:14:56.135 21908-21908/nl.hgrams.passenger I/﹕ continue init inside already:null
03-18 11:14:56.136 21908-21908/nl.hgrams.passenger I/﹕ continue init will copy to realm
03-18 11:14:56.137 21908-21908/nl.hgrams.passenger D/REALM﹕ jni: ThrowingException 7, Table has no columns, .
03-18 11:14:56.137 21908-21908/nl.hgrams.passenger D/REALM﹕ Exception has been throw: Table has no columns
03-18 11:14:56.138 21908-21908/nl.hgrams.passenger I/﹕ continue init error trying to add to realmAn exception was thrown in the copyToRealm method in the proxy class io.realm.PSTripRealmProxy: Annotation processor may not have been executed.
Does anyone have an ideea why does realm return me a "table has no columns" error?
EDIT:
This is my PSTrip class:
public class PSTrip extends RealmObject {
private boolean valid;
private String detail;
private String icon_small;
private double avgspeed;
private String type;
private RealmList<RealmObj> messages = new RealmList<RealmObj>();
private String travel_mode;
private String id;
private Owner_data owner_data;
private int distance;
private RealmObj errors;
private String name;
private String destination_status;
private double checkinLat;
private double checkinLng;
private double checkoutLng;
private double checkoutLat;
private String icon;
private String status;
private int update_interval;
private Destination destination;
private double elapsed;
private int checkout_time;
private int checkin_time;
private Route route;
private String owner;
private double delay;
private String vehicle;
private Flight flight;
#SerializedName("last_updated")
private int lastUpdated;
#SerializedName("steps")
private RealmList<TripStep> tripSteps = new RealmList<TripStep>();
private Group group;
private boolean isRoaming = false;
public boolean getIsRoaming() {
return isRoaming;
}
public void setIsRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
public int getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(int lastUpdated) {
this.lastUpdated = lastUpdated;
}
public RealmList<TripStep> getTripSteps() {
return tripSteps;
}
public void setTripSteps(RealmList<TripStep> steps) {
this.tripSteps = steps;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public Flight getFlight() {
return flight;
}
public void setFlight(Flight flight) {
this.flight = flight;
}
public boolean getValid() {
return valid;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public String getIcon_small() {
return icon_small;
}
public void setIcon_small(String icon_small) {
this.icon_small = icon_small;
}
public double getAvgspeed() {
return avgspeed;
}
public void setAvgspeed(double avgspeed) {
this.avgspeed = avgspeed;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RealmList<RealmObj> getMessages() {
return messages;
}
public void setMessages(RealmList<RealmObj> messages) {
this.messages = messages;
}
public String getTravel_mode() {
return travel_mode;
}
public void setTravel_mode(String travel_mode) {
this.travel_mode = travel_mode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Owner_data getOwner_data() {
return owner_data;
}
public void setOwner_data(Owner_data owner_data) {
this.owner_data = owner_data;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public RealmObj getErrors() {
return errors;
}
public void setErrors(RealmObj errors) {
this.errors = errors;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDestination_status() {
return destination_status;
}
public void setDestination_status(String destination_status) {
this.destination_status = destination_status;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getUpdate_interval() {
return update_interval;
}
public void setUpdate_interval(int update_interval) {
this.update_interval = update_interval;
}
public Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
public double getElapsed() {
return elapsed;
}
public void setElapsed(double elapsed) {
this.elapsed = elapsed;
}
public int getCheckout_time() {
return checkout_time;
}
public void setCheckout_time(int checkout_time) {
this.checkout_time = checkout_time;
}
public int getCheckin_time() {
return checkin_time;
}
public void setCheckin_time(int checkin_time) {
this.checkin_time = checkin_time;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public PSTrip() {
}
public double getDelay() {
return delay;
}
public void setDelay(double delay) {
this.delay = delay;
}
public PSTrip(String id) {
this.id = id;
}
public double getCheckoutLng() {
return checkoutLng;
}
public void setCheckoutLng(double checkoutLng) {
this.checkoutLng = checkoutLng;
}
#Override
public boolean isValid() {
return valid;
}
public double getCheckinLat() {
return checkinLat;
}
public void setCheckinLat(double checkinLat) {
this.checkinLat = checkinLat;
}
public double getCheckinLng() {
return checkinLng;
}
public void setCheckinLng(double checkinLng) {
this.checkinLng = checkinLng;
}
public double getCheckoutLat() {
return checkoutLat;
}
public void setCheckoutLat(double checkoutLat) {
this.checkoutLat = checkoutLat;
}
public boolean isRoaming() {
return isRoaming;
}
public void setRoaming(boolean isRoaming) {
this.isRoaming = isRoaming;
}
}
This is my TripStep class:
public class TripStep extends RealmObject{
#SerializedName("travel_mode")
private String travelMode;
#SerializedName("moving_time")
private int movingTime;
#SerializedName("moving_distance")
private int movingDistance;
private Polyline polyline;
private String vehicle;
private Route route;
#SerializedName("trip_id")
private int tripId;
#SerializedName("departure_stop")
private DepartureStop departureStop;
#SerializedName("arrival_stop")
private DepartureStop arrivalStop;
#PrimaryKey
private int id;
private Transit_details transit_details;
private RealmList<Step> steps = new RealmList<Step>();
private boolean hasStarted = false;
public Transit_details getTransit_details() {
return transit_details;
}
public void setTransit_details(Transit_details transit_details) {
this.transit_details = transit_details;
}
public String getTravelMode() {
return travelMode;
}
public void setTravelMode(String travelMode) {
this.travelMode = travelMode;
}
public int getMovingTime() {
return movingTime;
}
public void setMovingTime(int movingTime) {
this.movingTime = movingTime;
}
public int getMovingDistance() {
return movingDistance;
}
public void setMovingDistance(int movingDistance) {
this.movingDistance = movingDistance;
}
public Polyline getPolyline() {
return polyline;
}
public void setPolyline(Polyline polyline) {
this.polyline = polyline;
}
public String getVehicle() {
return vehicle;
}
public void setVehicle(String vehicle) {
this.vehicle = vehicle;
}
public Route getRoute() {
return route;
}
public void setRoute(Route route) {
this.route = route;
}
public int getTripId() {
return tripId;
}
public void setTripId(int tripId) {
this.tripId = tripId;
}
public DepartureStop getDepartureStop() {
return departureStop;
}
public void setDepartureStop(DepartureStop departureStop) {
this.departureStop = departureStop;
}
public DepartureStop getArrivalStop() {
return arrivalStop;
}
public void setArrivalStop(DepartureStop arrivalStop) {
this.arrivalStop = arrivalStop;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public RealmList<Step> getSteps() {
return steps;
}
public void setSteps(RealmList<Step> steps) {
this.steps = steps;
}
public boolean isHasStarted() {
return hasStarted;
}
public void setHasStarted(boolean hasStarted) {
this.hasStarted = hasStarted;
}
}
The rest are mostly google maps classes.
The PSTrip RealmList messages is empty.
the Route class contains a RealmList which is not empty (thats why I try doing copy to realm on it before)

Categories

Resources