When using firebase (or any database that aggregates data basing on ids) I nearly always have to keep track of a key of a given value. For example let's assume I have Location class with latitude and longitude fields. When I download if from firebase, besides its two fields, I also want to keep track of the key (node value generated with push() e.g. -K_esEYXNfMBNmgF3fO4) it was downloaded from so I may later update it, delete it etc. I see only two solutions:
Duplicate the data and add key value as another Location class field. That doesn't work nicely because I have to set the key value only after I executed push().
Create generic wrapper class that will keep key and object:
public class Key<T> {
private final String key;
private final T value;
public Key(String key, T value) {
this.value = value;
this.key = key;
}
public String key() {
return key;
}
public T value() {
return value;
}
}
I am using the second approach but it doesn't look really nice. I have this Key class basically throughout all my codebase and when using RxJava plenty of methods have a return type like this: Observable<Key<Location>> and that just looks ridiculous.
What you call ridiculous actually looks quite normal to me.
Alternatively you can include the key in the POJO and annotate it with #Exclude to exclude it from the serialization.
Follow up on #FrankvanPuffelen great answer, do what you want with the below pushkey
Read and Write Data on Android
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
Related
I have java objects which are are backed by a HashMap and thus do not have plain fields which can be discovered via reflection. For example:
public class City {
private final HashMap<String, String> internalMap = new HashMap<String, String>();
public String getId() {
return internalMap.get("id");
}
public void setId(String id) {
internalMap.put("id", id);
}
public String getName() {
return internalMap.get("name");
}
public void setName(String name) {
internalMap.put("name", name);
}
}
I want to use classes such as this an entity in Room without having to change its structure since I have many such classes which are auto-generated using code generation tools and there are specific reasons why they need to be backed by a HashMap. Each value of the HashMap should end up as a column in my database table (the key String is an internal implementation detail). Is it possible? Seems not to be at the moment due to how fields are discovered by the annotation processor.
UPDATE:
None of the answers were at all what I was looking for. I opened a new question without mentioning HashMap since that detail was not supposed to be relevant but all the answers latched on to it. See How to use Android Room with POJOs provided by an external library? for the updated question.
You can use TypeConverter for this.
For instance, you can use serialization provided by GSON to easily convert the map to serialized state and vice versa.
class MapConverter {
#TypeConverter
public String fromMap(HashMap<String, String> map) {
return new Gson().toJson(map);
}
#TypeConverter
public HashMap<String, String> fromString(String serializedMap) {
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
return gson.fromJson("serializedMap", type);
}
}
And in your entity class:
#Entity
#TypeConverters({MapConverter.class})
public class CityEntity {
//...
private final HashMap<String, String> internalMap;
//...
}
So the converter will be available for this entity to serialize the hashmap to string and vice versa.
Gson is just a possible solution, you can actually use whatever you want.
Room has it's own set of annotations - and if you do not want to have a field mapped, you have to indicate this towards the annotation processor by annotating the POJO as it may be required; eg. #Entity without assigning a tableName, as well the #Ignore above the field to ignore:
#Entity
public class City {
#Ignore
private final HashMap<String, String> internalMap = new HashMap<>();
/* concerning the second part of the question: */
public HashMap<String, Object> toHashMap() {
return this.internalMap;
}
}
besides those getters have the fundamental problem, that they assume all the keys would exist, despite the HashMap might not have been populated with all (or any) of those keys. and it's absurd to represent a city with two different types of object - while one has full control over which fields are being mapped and which are being ignored (one possible approach does not have to exclude the other here)... a method to return the HashMap might be useful, eg. in order to insert that into Firebase.
I'd rather go for fields holding the values, while nevertheless being able to return a HashMap:
#Entity(tableName = "cities")
public class City {
#ColumnInfo(name = "cityId")
#PrimaryKey(autoGenerate = true)
private int cityId = -1;
#ColumnInfo(name = "cityName")
private String cityName = null;
...
/* concerning the second part of the question: */
public HashMap<String, Object> toHashMap() {
HashMap<String, Object> values = new HashMap<>();
if(this.cityId != -1) {values.put( "id", this.cityId);}
if(this.cityName != null) {values.put("name", this.cityName);}
return values;
}
}
such a toHashMap() method also provides control, which fields the returned HashMap shall contain, while the example with the TypeConverter & GSON would (as it is) convert the whole HashMap.
Updating a field contains period (.) is not working as expected.
In docs, nested fields can be updated by providing dot-seperated filed path strings or by providing FieldPath objects.
So if I have a field and it's key is "com.example.android" how I can update this field (from Android)?
In my scenario I've to set the document if it's not exists otherwise update the document. So first set is creating filed contains periods like above and then trying update same field it's creating new field with nested fields because it contains periods.
db.collection(id).document(uid).update(pkg, score)
What you want to do is possible:
FieldPath field = FieldPath.of("com.example.android");
db.collection(collection).document(id).update(field, value);
This is happening because the . (dot) symbol is used as a separator between objects that exist within Cloud Firestore documents. That's why you have this behaviour. To solve this, please avoid using the . symbol inside the key of the object. So in order to solve this, you need to change the way you are setting that key. So please change the following key:
com.example.android
with
com_example_android
And you'll be able to update your property without any issue. This can be done in a very simple way, by encoding the key when you are adding data to the database. So please use the following method to encode the key:
private String encodeKey(String key) {
return key.replace(".", "_");
}
And this method, to decode the key:
private String decodeKey(String key) {
return key.replace("_", ".");
}
Edit:
Acording to your comment, if you have a key that looks like this:
com.social.game_1
This case can be solved in a very simple way, by encoding/decoding the key twice. First econde the _ to #, second encode . to _. When decoding, first decode _ to . and second, decode # to _. Let's take a very simple example:
String s = "com.social.game_1";
String s1 = encodeKeyOne(s);
String s2 = encodeKeyTwo(s1);
System.out.println(s2);
String s3 = decodeKeyOne(s2);
String s4 = decodeKeyTwo(s3);
System.out.println(s4);
Here are the corresponding methods:
private static String encodeKeyOne(String key) {
return key.replace("_", "#");
}
private static String encodeKeyTwo(String key) {
return key.replace(".", "_");
}
private static String decodeKeyOne(String key) {
return key.replace("_", ".");
}
private static String decodeKeyTwo(String key) {
return key.replace("#", "_");
}
The output will be:
com_social_game#1
com.social.game_1 //The exact same String as the initial one
But note, this is only an example, you can encode/decode this key according to the use-case of your app. This a very common practice when it comes to encoding/decoding strings.
Best way to overcome this behavior is to use the set method with a merge: true parameter.
Example:
db.collection(id).document(uid).set(new HashMap<>() {{
put(pkg, score);
}}, SetOptions.merge())
for the js version
firestore schema:
cars: {
toyota.rav4: $25k
}
js code
const price = '$25k'
const model = 'toyota.rav4'
const field = new firebase.firestore.FieldPath('cars', model)
return await firebase
.firestore()
.collection('teams')
.doc(teamId)
.update(field, price)
Key should not contains periods (.), since it's conflicting with nested fields. An ideal solution is don't make keys are dynamic, those can not be determined. Then you have full control over how the keys should be.
How can I change the naming of the nodes of my children in the image below?
questions_stats is a List<Integer>, I'm aware that I get integers as nodes Id because this is a List. I create each of the children randomly with a number between 0 and 1000. I set this ID as part of the object and to find it I loop trough the list. What I want is to set the "0671" as the Key of the Object at the moment I create it.
How should I define my object in order to access each child with an Id that I define as a String.
Each of the questions_stats is an object.
This is my UserProfile Class definition.
public class UserProfile implements Parcelable {
private List<Integer> questions_list;
private List<QuestionsStats> questions_stats;
private String country_name, share_code, user_name;
private int token_count;
private Boolean is_guest;
public UserProfile() {
}
public UserProfile(List<Integer> questions_list, List<QuestionsStats> questions_stats, String country_name, String share_code, String user_name, int token_count, Boolean is_guest) {
this.questions_list = questions_list;
this.questions_stats = questions_stats;
this.country_name = country_name;
this.share_code = share_code;
this.user_name = user_name;
this.token_count = token_count;
this.is_guest = is_guest;
}
}
I know I can set them using the child("0159").setValue(QuestionStats) individually.
But for my purpose I need to retrieve the data of the "user" as a whole and then iterate whithin questions_stats like it is a List.
How should I define my UserProfile class in order to achieve what I want?
Anybody could give me a hint?
How can I change the node names of my children in the image below?
Answer: There is no way in which you can change the names of the nodes from your Firebase database. There is no API for doing that. What can you do instead is to attach a listener on that node and get the dataSnapshot object. Having that data, you can write it in another place using other names. You cannot simply rename them from 0 to 0000, 1 to 0001 and so on.
Perhaps I should have asked for How to "Set" the node Id instead of "Change"
What I have is an List<QuestionsStats>, but when using an List<QuestionsStats> you get indexes as Keys, What I want is to have the same List<QuestionsStats> but instead of indexes, String Keys for each of my items.
So I changed my List for a Map<String, QuestionsStats>. Now the tricky part is when parceling the Object. You can use readMap() or writeMap() to parcel as shown here in this answer by #David Wasser, but it gives a warning:
Please use writeBundle(Bundle) instead. Flattens a Map into the parcel
at the current dataPosition(), growing dataCapacity() if needed. The
Map keys must be String objects. The Map values are written using
writeValue(Object) and must follow the specification there. It is
strongly recommended to use writeBundle(Bundle) instead of this
method, since the Bundle class provides a type-safe API that allows
you to avoid mysterious type errors at the point of marshalling.
So with the help of the comments in This Question I parceled using this code, note that I'm leaving the "easy" way commented in case somebody find it useful or have any comment on that :
protected UserProfile(Parcel in) {
// in.readMap(myMap, Object.class.getClassLoader());
myMap = new HashMap<>();
String[] array = in.createStringArray();
Bundle bundle = in.readBundle(Object.class.getClassLoader());
for (String s : array) {
myMap.put(s, (Object) bundle.getParcelable(s));
}
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// dest.writeMap(myMap);
Bundle bundle = new Bundle();
for (Map.Entry<String, Object> entry : myMap.entrySet()) {
bundle.putParcelable(entry.getKey(), entry.getValue());
}
Set<String> keySet = myMap.keySet();
String[] array = keySet.toArray(new String[keySet.size()]);
dest.writeStringArray(array);
dest.writeBundle(bundle);
}
Why I want this, well at the moment my list contains less than 100 items but it could grow up to a 1000, I'm no Pro, but I believe that if I already know the key of the item I'm interested in will be always better than having to iterate over the list to find it. In the end my main problem was the usage of a Map, I did not know howto.
I am trying to insert a POJO to Firebase. However, some of the fields don't seem to be parsed into Firebase, but there is no warning or error.
I have this POJO:
public class Group {
public String name;
public String admin;
public List<String> addedUsers;
public List<String> invitedUsers;
public Group(String name, String admin, ArrayList<String> addedUsers, ArrayList<String> invitedUsers) {
this.name = name;
this.admin = admin;
this.addedUsers = addedUsers;
this.invitedUsers = invitedUsers;
}
public Group() {
// Default constructor required because we have a non-default constructor as well.
}
}
I upload to Firebase by doing so:
DatabaseReference groupRef = ref.child("Groups");
ArrayList<String> addedUsers = new ArrayList<String>();
addedUsers.add("email1#gmail.com");
addedUsers.add("email2#gmail.com");
ArrayList<String> invitedUsers = new ArrayList<String>();
Group newGroup = new Group("GroupName",
"email1#gmail.com", addedUsers, invitedUsers
);
groupRef.push().setValue(newGroup);
I end up with this object in Firebase:
I have a secondary issue now, I manually inserted the data into Firebase, but now I cannot map the Lists onto my Java Object, and are mapped as null, I know I am able to download the data fine;
I'm not sure what you mean that lists are not supported, as it seems that they are supported.
Basic write operations
For basic write operations, you can use setValue() to save data to a
specified reference, replacing any existing data at that path. You can
use this method to:
Pass types that correspond to the available JSON types as follows:
String
Long
Double
Boolean
Map<String, Object>
List<Object>
Pass a custom Java object, if the class that defines it has a default
constructor that takes no arguments and has public getters for the
properties to be assigned.
Firebase supports key value mapping. So lists are not supported. Change it to Map type, keep email addresses as key and assign a boolean value true or false.
I am currently using Sugar ORM and Android Async Http Client for my Android application.
I read through the documentation of Sugar ORM and did exactly what is written there.
My HttpClient is using the singleton pattern and provides methods for calling some APIs.
Now comes the bad part about it. I am not able to save the data persistently into my database which is created by Sugar ORM.
Here is the method, that is calling an API:
public void getAvailableMarkets(final Context context, final MarketAdapter adapter) {
String url = BASE_URL.concat("/markets.json");
client.addHeader("Content-Type", "application/json");
client.addHeader("Accept", "application/json");
client.get(context, url, null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
Log.i(TAG, "Fetched available markets from server: " + response.toString());
Result<Markets> productResult = new Result<Markets>();
productResult.setResults(new Gson().<ArrayList<Markets>>fromJson(response.toString(),
new TypeToken<ArrayList<Markets>>() {
}.getType()));
ArrayList<Markets> marketsArrayList = productResult.getResults();
// This lines tells me that there are no entries in the database
List<Markets> marketsInDb = Markets.listAll(Markets.class);
if(marketsInDb.size() < marketsArrayList.size() ||
marketsInDb.size() > marketsArrayList.size()) {
Markets.deleteAll(Markets.class);
for(Markets m : marketsArrayList) {
Markets market = new Markets(m.getId(), m.getName(), m.getChainId(), m.getLat(),
m.getLng(), m.getBusinessHourId(), m.getCountry(), m.getZip(), m.getCity(),
m.getStreet(), m.getPhoto(), m.getIcon(), m.getUrl());
market.save();
adapter.add(market);
}
adapter.notifyDataSetChanged();
}
List<Markets> market = Markets.listAll(Markets.class);
// This lines proves that Sugar ORM is not saving the entries
Log.i(TAG, "The market database list has the size of:" + market.size());
}
});
}
This is what Logcat is printing:
D/Sugar: Fetching properties
I/Sugar: Markets saved : 3
I/Sugar: Markets saved : 5
I/RestClient: The market database list has the size of:0
Also I took a look at the Sugar ORM tag here at stackoverflow, but no answers or questions could give me a hint on how to solve that problem.
I am a newbie to the android ecosystem and would love any help of you guys to solve this problem.
Thanks in advance
I just solve it the same problem as you have.
It was a pain in the neck but after few hours I find out what caused this problem.
Using Sugar ORM you must not set id property as it's belongs to SugarRecord class,
otherwise ORM will try to update objects instead of insert them.
As I need to have field with my object id, I used json annotation to assign it to another field.
Last step was configure GSON to exclude fields without Expose annotation.
So my class looks like one below now:
public class MyClass
{
#Expose
#SerializedName("id")
private long myId;
#Expose
private String field1;
#Expose
private String field2;
#Expose
private byte[] field3;
#Expose
private double field4;
public MyClass() { }
// parametrized constructor and more logic
}
Cheers!