Recycler View Adding Previous Content On New Contents - android

Thanks for the help as always. I am making a firebase chat app and i ran into this bug and i can figure out what is happening.
Usually if i clear the database and start fresh, the error doesnt occur but
Whenever i send a message, an older received message is included in the new one in the recyclerview. i am lost and frustrated. I have searched through stackoverflow for solution to no positive result. Here is a screenshot of the error.
private void loadMessages() {
chatMessagesRef = db.getReference("ChatMessages").child(Common.currentUser.getMatric()).child(user_id);
adapter = new FirebaseRecyclerAdapter<Message, ChatMessageViewHolder>(
Message.class,
R.layout.single_message_item,
ChatMessageViewHolder.class,
chatMessagesRef
) {
#Override
protected void populateViewHolder(final ChatMessageViewHolder viewHolder, final Message model, int position) {
if (model.getFrom().equalsIgnoreCase(Common.currentUser.getMatric())) {
if (model.getType().equalsIgnoreCase("text")){
viewHolder.yourMessage.setText(model.getMessage());
viewHolder.yourMessage.setVisibility(View.VISIBLE);
viewHolder.theAll.setBackgroundColor(Color.WHITE);
}
} else if (model.getFrom().equalsIgnoreCase(user_id)){
if (model.getType().equalsIgnoreCase("text")){
viewHolder.messageText.setText(model.getMessage());
viewHolder.messageText.setVisibility(View.VISIBLE);
viewHolder.theAll.setBackgroundColor(Color.YELLOW);
}
}
}
};
messagesRecycler.setAdapter(adapter);
adapter.notifyDataSetChanged();
messagesRecycler.scrollToPosition(adapter.getItemCount() - 1);
adapter.cleanup();
}
private void sendTheMessage() {
String message = chatBox.getText().toString();
if (message.isEmpty()){
} else {
long date = System.currentTimeMillis();
messageRef = db.getReference("ChatMessages").child(Common.currentUser.getMatric()).child(user_id).push();
final String chatMessageId = messageRef.getKey();
final Message newMessage = new Message(message, "text", date, false, Common.currentUser.getMatric());
messageRef2 = db.getReference("ChatMessages").child(Common.currentUser.getMatric()).child(user_id);
messageRef2.child(chatMessageId).setValue(newMessage).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
messageRef3 = db.getReference("ChatMessages").child(user_id).child(Common.currentUser.getMatric());
messageRef3.child(chatMessageId).setValue(newMessage);
sendNotification();
chatBox.setText("");
}
});
}
}
public class Message {
private String message, type;
private long time;
private boolean seen;
private String from;
public Message() {
}
public Message(String message, String type, long time, boolean seen, String from) {
this.message = message;
this.type = type;
this.time = time;
this.seen = seen;
this.from = from;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public boolean isSeen() {
return seen;
}
public void setSeen(boolean seen) {
this.seen = seen;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}This is the database structure

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

Android/Firebase realtime-database how get only last message?

I'm using the firebase Database at the Android Studio. Code java. I use realtime database.
I'm doing a Chat app. I want to show users the last message in their inbox.
I have this database:
message: {
User uıd: {
Uid of the person he is talking to: {
random key: {
-date
-from
-message
-time
-type
}
}
}
I have ref to database als:
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
ChatsRef=FirebaseDatabase.getInstance().getReference().child("message").child(currentUserID);
I'm using this to get :
public void messageegetir(){
FirebaseRecyclerOptions<Messages> options =
new FirebaseRecyclerOptions.Builder<Messages>()
.setQuery(ChatsRef,Messages.class)
.build();
FirebaseRecyclerAdapter<Messages, ChatsViewHolder> adapter =
new FirebaseRecyclerAdapter<Messages, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull final Messages model) {
final String usersIDs = getRef(position).getKey();
final String[] retImage = {"default_image"};
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_list_model,viewGroup,false);
return new ChatsViewHolder(view);
}
};
chatlist.setAdapter(adapter);
adapter.startListening();
updateUserStatus("online");
}
my publıc statıc class :
public static class ChatsViewHolder extends RecyclerView.ViewHolder{
CircleImageView profileImage ;
ImageView onlinestatus;
TextView lastmessage , userName ;
public ChatsViewHolder(#NonNull View itemView) {
super(itemView);
profileImage =itemView.findViewById(R.id.messageprofileimageee);
userName =itemView.findViewById(R.id.messagenameee);
lastmessage =itemView.findViewById(R.id.messageinfooo);
onlinestatus =itemView.findViewById(R.id.onlinestatus);
}
}
Messages class :
public class Messages {
public String data, time, type, message, from ;
public Messages(){
}
public Messages(String data, String time, String type, String message, String from) {
this.data = data;
this.time = time;
this.type = type;
this.message = message;
this.from = from;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
}
enter image description here
How can I get those data and write them in a textview?
i suggest that you modify your database structure , denormalize it like it is recommended by firebase docs. see the link https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
And you will understand
I did a chat app and the way I did it is that I have two main roots and one is dedicated to getting the last sent message and it updated every time a new message is received and the other root is dedicated to storing a list of all messages between two users so I suggest doing something similar.

Multiple check item send params

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": []

Classmaper No setter found for the key generated by push

I want to display the messages of group chat in my recyclerview but i have this warning in logcat
I searched a lot for this error, I could not find the right solution ...
Model class
public class Groups {
private String groupName;
private String Admin;
private String push_id;
public MessageG messageG;
public Groups() {
}
public Groups(String groupName, String Admin, String push_id, MessageG messageG) {
this.groupName = groupName;
this.Admin = Admin;
this.push_id = push_id;
this.messageG = messageG;
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public String getAdmin() {
return Admin;
}
public void setAdmin(String admin) {
Admin = admin;
}
public String getPush_id() {
return push_id;
}
public void setPush_id(String push_id) {
this.push_id = push_id;
}
public MessageG getMessageG() {
return messageG;
}
public void setMessageG(MessageG messageG) {
this.messageG = messageG;
}
}
For the child:
public class MessageG
{
public String id;
public String name;
public String userid;
public String msg;
public String date;
public long time;
public MessageG() {}
public MessageG(String id, String name, String userid, String msg, String date, long time) {
this.id = id;
this.name = name;
this.userid = userid;
this.msg = msg;
this.date = date;
this.time = time;
}
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 getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
}
Listener of the button (send message):
btn_send_message.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String message = text_send.getText().toString();
if(message.equals(""))
{
Toast.makeText(GroupChatActivity.this, "Empty !", Toast.LENGTH_SHORT).show();
}
else
{
//SendMessageInfoToDatabase();
GroupNameRef = FirebaseDatabase.getInstance().getReference("Groups").child("Messages");
String id = GroupNameRef.push().getKey();
//---GET DATE
Calendar calForDate = Calendar.getInstance();
SimpleDateFormat currentDateFormat = new SimpleDateFormat("MMM dd, yyyy");
currentDate = currentDateFormat.format(calForDate.getTime());
//---------------------
//--- the time
Calendar calForTime = Calendar.getInstance();
SimpleDateFormat currentTimeFormat = new SimpleDateFormat("hh:mm");
currentTime = currentTimeFormat.format(calForTime.getTime());
//---------------------
assert id != null;
GroupMessageKeyRef = GroupNameRef.child(id);
Map<String, Object> messageInfoMap = new HashMap<>();
messageInfoMap.put("id", id);
messageInfoMap.put("name", CurrentUserName);
messageInfoMap.put("userid", fuser.getUid());
messageInfoMap.put("msg", message);
messageInfoMap.put("date", currentDate);
messageInfoMap.put("time", currentTime);
GroupMessageKeyRef.setValue(messageInfoMap);
text_send.setText("");
}
}
});
My adapter:
public class GroupMessageAdapter extends RecyclerView.Adapter<GroupMessageAdapter.GroupMessageViewHolder>
{
public static final int MSG_RECEIVERS = 1;
public static final int MSG_SENDER = 0;
private List<Groups> mMessageList;
private Context mContext;
public GroupMessageAdapter(List<Groups> mMessageList, Context mContext) {
this.mMessageList = mMessageList;
this.mContext = mContext;
}
#NonNull
#Override
public GroupMessageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
if(viewType == MSG_SENDER)
{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_sender, parent, false);
GroupMessageViewHolder gmvh = new GroupMessageViewHolder(view);
return gmvh;
}
else
{
View view = LayoutInflater.from(mContext).inflate(R.layout.chat_item_receivers, parent, false);
GroupMessageViewHolder gm = new GroupMessageViewHolder(view);
return gm;
}
}
public class GroupMessageViewHolder extends RecyclerView.ViewHolder
{
private TextView messages_textView;
public GroupMessageViewHolder(#NonNull View itemView)
{
super(itemView);
messages_textView = itemView.findViewById(R.id.group_chat_text_display);
}
}
#Override
public void onBindViewHolder(#NonNull final GroupMessageViewHolder groupMessageViewHolder, int position)
{
Groups groups = mMessageList.get(position);
groupMessageViewHolder.messages_textView.setText(groups.getMessageG().getMsg());
}
#Override
public int getItemCount()
{
return mMessageList.size();
}
#Override
public int getItemViewType(int position)
{
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
if(mMessageList.get(position).getMessageG().getUserid().equals(firebaseUser.getUid()))
{
return MSG_SENDER;
}
else
{
return MSG_RECEIVERS;
}
}
}
The error is :
W/ClassMapper: No setter/field for (KEY generated by push) found on
class
My database:
enter image description here

How can I save an object efficiently in Android

I have an object which I for now save using SharedPreferences like this:
public String getActiveTripString(Context con) {
return preferences.getString(ACTIVE_TRIP, "-1");
}
public void setActiveTripString(Context context, String string) {
setString(context, string, ACTIVE_TRIP);
}
public PSTrip getActiveTrip(Context context) {
String active = getActiveTripString(context);
PSTrip psTrip = null;
if (active.contentEquals("-1")) {
return null;
} else {
try{
psTrip = JsonUtil.jsonToObject(active, PSTrip.class);
}catch (Exception e){
Log.i("","getActiveTrip error is:" + e.getMessage());
}
return psTrip;
}
}
public void setActiveTrip(PSTrip psTrip, Context context) {
try{
setActiveTripString(context, JsonUtil.objectToJson(psTrip, PSTrip.class));
}catch (Exception e){
Log.i("","setActiveTrip error is:" + e.getMessage());
}
}
Where I have function as you can see, that create a json and then save it as a string in SharedPrefferences. But The object is BIG, and the more I add into it, the app start to be more laggy until it's unresponsive.
I also need to use this object in a lot of places, so I always need to call:
GetActiveTrip to get it, make my modifications, then SetActiveTrip to save it.
I'm looking for a more efficient way to save it. I tried with REALM, to save it in a database, but because my object is so big, and modified in a lot of places, I did not quite manage to make it work, Having to call Realm a lot just to add items in the database, in order to have managed database items, so I can add them in my object, and so on. Which also I think might be memory consuming. And It crashes a lot with realm exceptions.
Any other way I could do this? Is saving to a file more efficient than to Shared Preferences? As I saw in Android Monitor, analysing my traces, the GSON function that creates the JSON takes a lot of resources.
Any suggestions what I could use?
EDIT: My object:
public class PSTrip extends RealmObject {
private boolean valid;
private String type;
private String travel_mode;
#PrimaryKey
private String id;
private Owner_data owner_data;
private int distance;
private String name;
private double checkinLat;
private double checkinLng;
private double checkoutLng;
private double checkoutLat;
private String icon;
private String status;
private Destination destination;
private int checkout_time;
private int checkin_time;
private Route route;
private String owner;
private String vehicle;
private Flight flight;
#SerializedName("last_updated")
private int lastUpdated;
#SerializedName("steps")
private RealmList<TripStep> tripSteps;
private RealmList<Record> records;
#SerializedName("planned_route")
private Planned_Route plannedRoute;
private Group group;
private float emissions;
private Co2PerKm co2_per_km;
private int update_interval;
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 String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 Destination getDestination() {
return destination;
}
public void setDestination(Destination destination) {
this.destination = destination;
}
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 PSTrip(String id) {
this.id = id;
}
public double getCheckoutLng() {
return checkoutLng;
}
public void setCheckoutLng(double checkoutLng) {
this.checkoutLng = checkoutLng;
}
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;
}
public Planned_Route getPlannedRoute() {
return plannedRoute;
}
public void setPlannedRoute(Planned_Route plannedRoute) {
this.plannedRoute = plannedRoute;
}
public boolean isValid() {
return valid;
}
public float getEmissions() {
return emissions;
}
public void setEmissions(float emissions) {
this.emissions = emissions;
}
public Co2PerKm getCo2_per_km() {
return co2_per_km;
}
public void setCo2_per_km(Co2PerKm co2_per_km) {
this.co2_per_km = co2_per_km;
}
public void setValid(boolean valid) {
this.valid = valid;
}
public int getUpdate_interval() {
return update_interval;
}
public void setUpdate_interval(int update_interval) {
this.update_interval = update_interval;
}
public RealmList<Record> getRecords() {
return records;
}
public void setRecords(RealmList<Record> records) {
this.records = records;
}
}
Where: Route, Destination are the google maps object, if you are familiar with them, you know what they include and their size;
TripStep = similar with the STEP object from google BUT, it includes 2 arrays:
private RealmList<StopInfo> filteredLocations = new RealmList<>();
private RealmList<StopInfo> rawLocations = new RealmList<>();
In which I have to add a new location every 5-6 seconds in the rawLocations.
Add a new location each time the rawlocation I get is farther than x metres from the last rawLocation I got.
Getting the Object from Preferences, deserialising, getting the latest TripStep and adding the new Location to the filteredLocations and rawLocations seems to take a log of memory. So This is what I think is the problem
After all, I chose to use Realm, instead of shared preferences, it's more efficient, and even if I still have some issues with the changes I make to my file, I'm getting to a stable version quickly.
It has it's downsides (some REALM objects are not serialised correctly by GSON, and you will need to use jackson, and also not being able to use functions inside your model, or that it supports just primitives is a big issue with it, but if you manage to go over this, it's worth it)
Would not suggest adding Realm database to a project that is already big

Categories

Resources