I have an object like below,
class LocationData{
String time;
String name;
String address;
}
for this object i have created getter setter.
By using service i fill this above model and save into room database.
whenever user open my app i just update the room database data to server using API.
Now sometimes the time duplication occurred. How to remove the object from array based on time. time should be unique.
You can use the extension function distinctBy. If you have an array of LocationData objects called allLocations it would be
val distinctLocations = allLocations.distinctBy { it.time }
Note distinctLocations will be a List; if you want it to be an array, use toTypedArray()
Related
I have following object:
public class Cart {
public String id;
public List<Map<Product, Double>> productsInCart;
}
In this key itself is a complex object, how to do it in firestore?
Also above object can be redesigned as following
public class Cart {
public String id;
public Map<Product, Double> productsInCart;
}
Firestore does not have any sense of "complex" keys or properties. Fields and nested object property names must be strings. If you need to store something more complex, you will need to somehow reduce it down to a unique string. One option is to use a hash of the data in the object, but you're better off redesigning your object to simply use strings as keys.
With cloud firestore, you can convert a document to your object with document.toObject(YourClass.class); where the class's variables match those in your database. However, if one of the variables in the database is a reference, which data type would you use in the java class? Note that I need to not only store it in my data model but retrieve it and set it with the override methods of the form:
protected MyDataModel(Parcel in) {
mString = in.readString();
}
and
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(mString);
}
If I use a DocumentReference, then in writeToParcel(), how would I write it? Also, how would I read it in the protected Parcel in constructor? I have tried writeSerializable() and readSerializable() but DocumentReference does not implement Serializable.
I haven't used the Java API yet but I imagine you'll want to use the DocumentReference type. Here are some links in the firebase documentation:
DocumentReference
CollectionReference
getDocumentReference
If you need to serialize a DocumentReference, use its getPath() method to get a string that describes the document's location in the database. To deserialize that path string back into a DocumentReference, use FirebaseFirestore.getInstance().document(path).
When you have conversions like this to make, sometimes it more convenient to write all the code yourself rather than using the built-in object serialization provided by the Firestore SDK.
I had the same problem with document.toObject(YourClass.class);
I have an Event class, this class contains the id (document id) and a reference to another collection subCategoryReference.
I have created simples converters on my Event
For example:
val event = document
.toObject(Event::class.java)
.withId<Event>(document.id)
.withReference<Event>((document.data["subCategoryReference"] as DocumentReference).path)
In my Event class as you guessed I have two function withId and withReference
that look like this:
fun <T : Event?> withId(id: String): T {
this.id = id
return this as T
}
fun <T : Event?> withReference(reference: String): T {
this.subCategoryRef = reference
return this as T
}
Your class variables must have different names from your firestore variables/fields (just the variables you want to apply the converter on) - see the pic below
In my case on firestore, the reference field (variable) called subCategoryReference and in the Event class the variable name is subCategoryRef.
Let me know if you didn't get me.
I hope it helps...
Firestore console
Event Class
Thanks in advance.
I have scenario where i wanted to check the data difference between existing and new realm model object.
Example
public class PostModel extends RealmObject {
#Required
#PrimaryKey
#Index
private String postId;
private String message;
}
Let say we have two objects
Old
PostModel old = new PostModel("one", "Welcome");
realm.copyToRealm(old);
New Object
PostModel newOne = new PostModel("one", "Welcome to World");
before updating the old object with newOne should check data change, if change is there then should insert in the realm, like below
realm.dirtyCheckAndUpdate(old, newOne);
//underlying it should do below
Getting the record with id "one"
Check the difference between db record and new record (!old.message.equalsIgnore(newOne.message)).
if change is there then copyToRealmOrUpdate() should happen.
I just gave an example, i need to to this for complex RealmModel with relationship.
Why do you need to check? You can just call copyToRealmOrUpdate()? It will update data regardless, but if it overrides the data with the same data the end result is the same.
Otherwise, you will be forced to implement all the checking yourself, which is time-consuming and error-prone. You could also make your own annotation processor that generated the logic for you. It would look something like:
public boolean compare(PostModel m1, PostModel m2) {
if (!m1.getId().equals(m2.getId()) return false;
if (!m1.getMessage().equals(m2.getMessage()) return false;
if (!PostModelReference.compare(m1.getRef(), m2.getRef()) return false; // Recursive checks
}
I have following class
public class Student extends RealmObject{
private int studentID;
private String studentName;
// getters and setters here
}
Then I try to set a value to a already created student object
student.setStudentName("Peter");
Then I get following error
java.lang.IllegalStateException: Mutable method call during read
transaction.
In order to overcome this I have to do it as follows
Realm realm = Realm.getInstance(this);
realm.beginTransaction();
student.setStudentName("Peter");
realm.commitTransaction();
I don't want to persist this change in the database. How can I just set/change a value to an realm object variable without always persisting it to the database?
If you want to modify the object in a non-persisted manner, you need an unmanaged copy of it.
You can create a copy using realm.copyFromRealm(RealmObject realmObject); method.
When you are using Realm.createObject(), the object is added to the Realm and it only works within a write transaction. You can cancel a transaction and thereby discard the object.
Moreover, you can use your model class as a standalone class and create objects in memory (see http://realm.io/docs/java/0.80.0/#creating-objects for details). If you need to persist the objects, you can use the Realm.copyToRealm() method.
You might want to create a new Model. And your new model should implement RealmModel.
public class StudentRM extends RealmModel{
private int studentID;
private String studentName;
// Constructors here
// getters and setters here
}
Now you can do this.
studentRm.setStudentName("Peter"); //Setting Vale Or
studentRm.addAll(student); //Add all value from DB
studentRm.setStudentName("Jhon"); //It won't change DB anymore
studentRm.getStudentName(); // "Jhon"
You can use realm.cancelTransaction();, instead of realm.commitTransaction();
In android, I'm using model classes with methods to handle the data manipulation. My data is brought in from webservices as json. I'm contemplating the possibility of using JSONObjects to store the values of class level attributes. But, I don't know of a way to use the JSONObj as the "holder" variable and create access methods. I don't want to predetermine these methods, as jsonRepository should hold the values, not always known at design time
For example, I'd like to have:
public class User {
private JSONObject jsonAttributes;
public User(String json) {
this.jsonAttributes= new JSONObject(json);
}
[IMPLICIT attribute access methods]
public string Prop1() returns jsonAttributes.getString("prop1");
public string Prop1(String newProp1) returns jsonAttributes.putString("prop1",newProp1);
public string Prop2() returns jsonRepository.getString("id");
public string Prop2(String newProp2) returns jsonAttributes.putString("prop2",newProp2);
....
from outside this class then, I would access the attributes simply...
User myUser = new User(someValidJson);
String myString = myUser.Prop1
Misguided? If not, how does one manage implicit property setting/getting?
As was mentioned in the comment above, why not create your user class, with all of the relevant memeber variables, and simply parse your JSON data in order to populate the ionformation in your user class.
There are a lot of ways you can do this, but I would consider using the builder pattern, as it is flexible, which could be useful if your JSON data changes in the future.