Android Firebase and Converting Hashmap back to Object - java

I'm pulling out information into a series of classes using the Firebase SDK in Android. My classes do indeed contain my data, but on trying to extract my data of something as the same class, I get:
java.lang.ClassCastException: java.util.HashMap cannot be cast to CustomItem
I have a class, called CustomItems, that has:
public Map<String, CustomItem> Items;
I'm loading this, by setting the following in the onDataChange event.
Items = (HashMap<String, CustomItem>) dataSnapshot.getValue();
Anyhow, on trying to read this information by using CustomItem item = Items.get('key'), shows me the correct object name of CustomItem in Android Studio and it's Intellisense, however always returns a Hashmap.
Having written this so far, Im wondering if I now need to actually iterate through the children to set a new CustomItem as
item = child.getValue(CustomItem.class);
And then add that item to a List in CustomItems.

Related

Retrieving ArrayList of Custom objects in firebase

How would you go about storing and retrieving an ArrayList of custom objects in firebase? In my android application, I store and retrieve an array as follows
Storage:
ArrayList<GameQRCode> qrCodes = new ArrayList<>();
qrCodes.add(new GameQRCode("name1", "value1"));
qrCodes.add(new GameQRCode("name2", "value2"));
qrCodes.add(new GameQRCode("name3", "value3"));
User user = new User("myUsername");
user.setQrCodes(qrCodes);
db.collection("users").document("myUsername").set(user);
Retrieval:
db.collection("users").document("myUsername").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
ArrayList<GameQRCode> testList = (ArrayList<GameQRCode>) task.getResult().get("qrCodes");
}
});
However, when I try to use the retreived ArrayList, I get an error message like follows...
GameQRCode qrCode = qrCodes.get(position);
java.util.HashMap cannot be cast to com.example.qracutie.GameQRCode
Your help is greatly appreciated
Firestore doesn't remember the type of custom object you used to in your collection generic type, so you can't simply cast it the way you put it in after you get the document back. The error message is telling you that it stored data as a Map instead of your custom object type. It will be your responsibility to deal with that Map directly, pulling values out of it and mapping them back into your custom object. This means that you should probably pull data out like this:
List<Map<String, Object> testList =
(List<Map<String, Object>>) task.getResult().get("qrCodes");
In fact, you should be aware that Firestore will internally map everything to one of these basic types: Map, List, String, Integer/Long, Boolean, null. You should expect to get only these types, and you should probably also check the types of instanceof before you cast anything at all, in order to make sure that you never make an incorrect cast at runtime.

How do I retrieve video custom labels through the RestFB API using Java?

I'm creating a java application that pulls data from facebook videos using RestFB. How can I retrieve the custom labels from each video?
Although I'm able to pull the normal data from each video, there doesn't seem to be any RestFB function that gets custom labels.
I've tried creating my own function by copying the RestFB source code for getting the title and then changing it according to the data I need, but that doesn't seem to work.
The custom labels field is missing atm in RestFB, so you can wait until a new version is released or write a custom video type like this:
public class CustomLabelsVideo extends Video {
#Facebook("custom_labels")
private List<String> customLabels = new ArrayList<>();
public List<String> getCustomLabels() {
return customLabels;
}
public void setCustomLabels(List<String> customLabels) {
this.customLabels = customLabels;
}
}
You need to use this type in the fetchObject method, and don't forget to add the custom_labels string to the fields you fetch.

How to get media details(title, album, etc) from JavaFX Media object and add details to ObservableList?

I have created an ArrayList of media file paths and i want to get details of media file like title and album info in my JavaFX application. I want to add these details in ObservableList. So I created an iterator which gives path of all media files. Inside iterator loop, I have created a Media object. To get media information from Media object, I have created metadata event listener. I got media information in lambda function but i can't able to use them outside of lambda function. If i add info in ObservableList inside event listener lambda function than many null values inserting because of meta data iteration and only one useful information is inserting.
Here is my code:
ObservableList<PlayListModel> playListData = FXCollections.observableArrayList();
Iterator<JMPPlayListItem> it = playList.getIterator();
while(it.hasNext()) {
listMedia = new Media(it.next().getPath());
PlayListModel playListItem = new PlayListModel();
listMedia.getMetadata().addListener((MapChangeListener.Change<? extends String, ? extends Object> c)-> {
if (c.wasAdded()) {
if ("artist".equals(c.getKey())) {
playListItem.setArtist(c.getValueAdded().toString());
} else if ("title".equals(c.getKey())) {
// It prints title of song
System.out.println(c.getValueAdded().toString());
playListItem.setTitle(c.getValueAdded().toString());
} else if ("album".equals(c.getKey())) {
playListItem.setAlbum(c.getValueAdded().toString());
}
}
});
// It print null
System.out.println(playListItem.getTitle());
playListData.add(playListItem);
}
System.out.println(c.getValueAdded().toString()) is printing title of song but outside of lambda function System.out.println(playListItem.getTitle()) prints null. It means playListItem object's values isn't changing. I tried making playListItem final but wouldn't help. I also tried initializing playListItem object and playListData.add(playListItem) inside lambda function but it inserts title with many null title values because of event listener iteration.
I also tested with local variables but I'm not able to get values outside of listener lambda function.
I solved this problem. My solution is pass Media object in bean class's constructor and create another method in bean class that will retrieve media information and update bean object. This method is called through constructor. Now add this bean class's object in ObservableList. Observable list get updated automatically when media information event is fired. Now i can render tableview using ObservableList and using table.refresh() method, i can refresh table data when event is fired.

JavaFX: Create custom data attributes for nodes

I am currently in need of custom attributes which I can fetch anytime. Is there any way to create custom data attributes for nodes and then get those values in javafx?
Lets assume I have the the follwing Button.
<Button text="Im a button" fooBar="I hold some value" />
Similar to: https://developer.mozilla.org/de/docs/Web/Guide/HTML/Using_data_attributes
Now in HTML I could simply do the following:
<div id="example" data-foobar="I hold some value"></div>
Then I could easily get the data like this:
document.getElementById("example").dataset.foobar;
Edit: I need more than 1 data property for a node because a node can hold various information.
The data can be stored in the properties ObservableMap of a Node
Node node = ...
node.getProperties().put("foo", "bar");
...
Object foo = node.getProperties().get("foo");
Note however that some layout properties use this map too, so no property names similar to javafx properties / "static" properties should be used as key. To be sure you could create a custom key class that does not return true if an object of another type is passed as parameter to equals.
To solve your problem you should to use userData it can be any object that you need.
node.setUserData("Hello world");
node2.setUserData(123);
etc.
If you need to set multiple values you can save your values in an array, list, json etc.
ArrayList<String> vals = new ArrayList();
vals.add("Hello");
vals.add("World");
node3.setUserData(vals);
//some code
ArrayList<String> result = (ArrayList) node3.getUserData();

What's the easiest way to access listview item string?

I've got a listview and I want to start a new activity when clicking on an item in that listview. How do I access the variables of that item from the new activity?
Edit: My listview is populated via an Asynctask and an RSS Feed. I want to access one of the items in the array and read out its url.
Method 1:
you can store it in an object of a custom class (which implements Serilizable) on click of listview and pass that object via intent. Make sure :
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
Method 2(not recommended):
Create a static custom class and store the variables in onclick to that class instance.
for Static Class A {...}
//To pass
A.variable = "stored value";
//retrieve
String s = A.variable;
Method 3
Use SharePreferences. Recommended only if you need to remember what user clicked last time he was using the app.

Categories