Setter is not setting value to java object - java

I'm trying to set key (firebase key) to my java object TaskModel. But after using setter when I'm trying to retrieve data using getter. It is returning null.
Database Structure
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
taskModel.setTaskID(dataSnapshot1.getKey());
taskModel = dataSnapshot1.getValue(TaskModel.class);
Log.d("myadaptor", taskModel.getTaskID());
list.add(taskModel);
}
Please help me set key to my object!
TaskModel.java
public class TaskModel {
private String taskTitle;
private String dueDate;
private String taskDescription;
private String taskID;
public String getTaskID() {
return taskID;
}
public void setTaskID(String taskID) {
this.taskID = taskID;
}
public String getTaskTitle() {
return taskTitle;
}
public void setTaskTitle(String taskTitle) {
this.taskTitle = taskTitle;
}
public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public TaskModel(String taskTitle, String dueDate, String taskDescription) {
this.taskTitle = taskTitle;
this.dueDate = dueDate;
this.taskDescription = taskDescription;
}
public TaskModel(){
}
}

Here in your old code, you are assigning ID to taskModel, after that you initializing taskModel as new object from dataSnapShot. And in dataSnapShot you have null as id. SO it is like overridden of id:
taskModel.setTaskID(dataSnapshot1.getKey());
taskModel = dataSnapshot1.getValue(TaskModel.class);
Update the position of line:
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren()){
taskModel = dataSnapshot1.getValue(TaskModel.class);
taskModel.setTaskID(dataSnapshot1.getKey());
Log.d("myadaptor", taskModel.getTaskID());
list.add(taskModel);
}

Related

Firebase returning a null dataSnapshot when loading into nested objects

I'm trying to load an object from my database but the dataSnapshot is not returning anything. I have a structure like this:
This is my Event object:
public class Event implements Serializable {
private String eventName, eventDescription;
private Author author;
private Venue venue;
private ArrayList<Comment> comments;
private ArrayList<Like> likes;
public Event() {
}
public Event(#NonNull String eventName, String eventDescription, Author author, Venue venue) {
this.eventName = eventName;
this.eventDescription = eventDescription;
this.author = author;
this.venue = venue;
public String getEventName() {
return eventName;
}
public void setEventName(String eventName) {
this.eventName = eventName;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public Venue getVenue() {
return venue;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
public String getEventDescription() {
return eventDescription;
}
public void setEventDescription(String eventDescription) {
this.eventDescription = eventDescription;
}
public List<Comment> getComments() {
return comments;
}
public void setComments(ArrayList<Comment> comments) {
this.comments = comments;
}
public List<Like> getLikes() {
return likes;
}
public void setLikes(ArrayList<Like> likes) {
this.likes = likes;
}
}
And this is my code:
Event event;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.child("Event").child("0").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
event = dataSnapshot.getValue(Event.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
The event object comes back as null even though I'm pretty sure the path is correct

Android Firebase Realtime database error when getting a nodes children

I have a pretty weird problem. This code was working a few days ago however now it is crashing my application. I am trying to loop through a nodes children.
private void getInfo()
{
FirebaseDatabase.getInstance().getReference()
.child("ForumResponses").child(forumID).addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
for(DataSnapshot snap : dataSnapshot.getChildren())
{
ForumResponses forumResponses = snap.getValue(ForumResponses.class);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
If i remove the below line of code the application does not crash. Why is this?
ForumResponses forumResponses = snap.getValue(ForumResponses.class);
Below is error log
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.util.HashMap to int
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertInteger(com.google.firebase:firebase-database##16.1.0:351)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToPrimitive(com.google.firebase:firebase-database##16.1.0:272)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.1.0:197)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToType(com.google.firebase:firebase-database##16.1.0:178)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$100(com.google.firebase:firebase-database##16.1.0:47)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##16.1.0:580)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.deserialize(com.google.firebase:firebase-database##16.1.0:550)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database##16.1.0:420)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database##16.1.0:214)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database##16.1.0:79)
at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database##16.1.0:212)
at Activities.ViewForumResponseActivity$1.onDataChange(ViewForumResponseActivity.java:95)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.1.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.1.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.1.0:55)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
Below is Forum Response Class
public class ForumResponses
{
private String id;
private String response;
private String author;
private String authorID;
private String usersWhoLiked;
private int liked;
public ForumResponses()
{
/*
Default no arg constructor
*/
}
public ForumResponses(String id, String response, String author, String authorID, String usersWhoLiked, int liked)
{
this.id = id;
this.response = response;
this.author = author;
this.authorID = authorID;
this.usersWhoLiked = usersWhoLiked;
this.liked = liked;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getResponse()
{
return response;
}
public void setResponse(String response)
{
this.response = response;
}
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
}
public String getAuthorID()
{
return authorID;
}
public void setAuthorID(String authorID)
{
this.authorID = authorID;
}
public String getUsersWhoLiked()
{
return usersWhoLiked;
}
public void setUsersWhoLiked(String usersWhoLiked)
{
this.usersWhoLiked = usersWhoLiked;
}
public int getLiked()
{
return liked;
}
public void setLiked(int liked)
{
this.liked = liked;
}
}
Below is image of database
You are getting the following error:
com.google.firebase.database.DatabaseException: Failed to convert a value of type java.util.HashMap to int
Because the type of your liked field inside your ForumResponses class is int and in your database as the field is actual an object. To solve this, either convert the field in the database to int or change the type of the field in your ForumResponses class to a Map<String, Object>.

Cannot set data to Java Model

I have a model below which i use to add my data and get it's properties when a user selects an option. Unfortunately i am unable to get the logic right. Kindly help with the best way to set data to a model using an array.
Unfortunately i get the error Data cannot be applied to Data[]
Model
public class Data
{
private String isVerified;
private String providerType;
private String modifiedAt;
private String modifiedBy;
private String provider;
private String id;
private String accountNumber;
private String accountName;
private String createdBy;
private String isDefault;
private String createdAt;
private String userId;
private String providerId;
public String getIsVerified ()
{
return isVerified;
}
public void setIsVerified (String isVerified)
{
this.isVerified = isVerified;
}
public String getProviderType ()
{
return providerType;
}
public void setProviderType (String providerType)
{
this.providerType = providerType;
}
public String getModifiedAt ()
{
return modifiedAt;
}
public void setModifiedAt (String modifiedAt)
{
this.modifiedAt = modifiedAt;
}
public String getModifiedBy ()
{
return modifiedBy;
}
public void setModifiedBy (String modifiedBy)
{
this.modifiedBy = modifiedBy;
}
public String getProvider ()
{
return provider;
}
public void setProvider (String provider)
{
this.provider = provider;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getAccountNumber ()
{
return accountNumber;
}
public void setAccountNumber (String accountNumber)
{
this.accountNumber = accountNumber;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getCreatedBy ()
{
return createdBy;
}
public void setCreatedBy (String createdBy)
{
this.createdBy = createdBy;
}
public String getIsDefault ()
{
return isDefault;
}
public void setIsDefault (String isDefault)
{
this.isDefault = isDefault;
}
public String getCreatedAt ()
{
return createdAt;
}
public void setCreatedAt (String createdAt)
{
this.createdAt = createdAt;
}
public String getUserId ()
{
return userId;
}
public void setUserId (String userId)
{
this.userId = userId;
}
public String getProviderId ()
{
return providerId;
}
public void setProviderId (String providerId)
{
this.providerId = providerId;
}
#Override
public String toString()
{
return "ClassPojo [isVerified = "+isVerified+", providerType = "+providerType+", modifiedAt = "+modifiedAt+", modifiedBy = "+modifiedBy+", provider = "+provider+", id = "+id+", accountNumber = "+accountNumber+", accountName = "+accountName+", createdBy = "+createdBy+", isDefault = "+isDefault+", createdAt = "+createdAt+", userId = "+userId+", providerId = "+providerId+"]";
}
}
Below is my method to add data to the model
private void addToWallets(Data walletData) {
Data wallet = new Data();
wallet.setId(walletData.getId());
wallet.setAccountNumber(walletData.getAccountNumber());
wallets.add(wallet);
}
I add the response from the server to my method that i created to add data to the model:
if (response.isSuccess()){
loading.dismiss();
Data[] wallets = response.body().getData();
addToWallets(wallets);
}
An array of Data can't be converted to a single Data object.
I suppose that this is what you want:
Data[] wallets = response.body().getData();
for (Data wallet : wallets) {
addToWallets(wallet);
}

Android Firebase Database - not appropriate Object conversion from Database structure

My database structure is like this:
users
8aWcF6GQmpezfJkVnW5uYoJ2wtI3
email: "jack"#mail.com"
height: "180cm"
imgUrl: "https://www.goldennumber.net/wp-content/uploads..."
matches
WEZ36bsEFXQtrJWQJVT3KMtsgQC3: true
8oqmrMVZ57XXlunIAUEeBgKFZ0h2: true
uid: "8aWcF6GQmpezfJkVnW5uYoJ2wtI3"
username: "jack"
I am trying to convert this structure to this object:
public class UserMatchDTO {
private String uid;
private String username;
private String height;
private String imgUrl;
private String email;
private HashMap<String, Boolean> userMatches = new HashMap<>();
public UserMatchDTO() {
}
public UserMatchDTO(String uid, String username, String height, String imgUrl, String email, HashMap<String, Boolean> userMatches) {
this.uid = uid;
this.username = username;
this.height = height;
this.imgUrl = imgUrl;
this.email = email;
this.userMatches = userMatches;
}
public String getUid() {
return uid;
}
public String getUsername() {
return username;
}
public String getHeight() {
return height;
}
public String getImgUrl() {
return imgUrl;
}
public HashMap<String, Boolean> getUserMatches() {
return userMatches;
}
public void setUserMatches(HashMap<String, Boolean> userMatches) {
this.userMatches = userMatches;
}
public String getEmail() {
return email;
}
}
Here is the method where I convert this to my object:
final List<UserMatchDTO> userMatchDTOs = new ArrayList<>();
databaseReference.child("users").addValueEventListener(new
ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
userMatchDTOs.add(userMatchDTO);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
However, when I debug this, the userMatches HashMap is always size 0. So why child "matches" from "user" is not converted to HashMap?
Here is what the snapshot looks like:
DataSnapshot { key = 8oqmrMVZ57XXlunIAUEeBgKFZ0h2, value = {email=jack#mail.com, height=180cm, uid=8aWcF6GQmpezfJkVnW5uYoJ2wtI3, imgUrl=https://www.goldennumber.net/wp-content/uploads/2013/08/florence-colgate-england-most-beautiful-face.jpg, username=jack, matches={WEZ36bsEFXQtrJWQJVT3KMtsgQC3=true, 8oqmrMVZ57XXlunIAUEeBgKFZ0h2=true}} }
Ok, so i manage to solve this, but I am not sure if this is good solution.
I just map the response to Object first and then cast this to the HashMap.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot matchSnapshot : dataSnapshot.getChildren()){
UserMatchDTO userMatchDTO = matchSnapshot.getValue(UserMatchDTO.class);
Object object = matchSnapshot.child("matches").getValue();
if(object != null){
userMatchDTO.setUserMatches((HashMap<String, Boolean>) object);
}
userMatchDTOs.add(userMatchDTO);
}
Is any better solution for this?

Correct way to update a Realm database?

This is the structure of my Realm database:
public class ARDatabase extends RealmObject
{
#PrimaryKey
private String uid;
private String namex;
private String desc;
private boolean isVideo;
private boolean isDeleted;
private String urlImg;
private String urlApp;
private int updates;
private boolean isDownloaded;
private String location;
public ARDatabase(){}
public String getUid()
{
return uid;
}
public void setUid(String uid)
{
this.uid = uid;
}
public String getNamex()
{
return namex;
}
public void setNamex(String namex)
{
this.namex = namex;
}
public String getDesc()
{
return desc;
}
public void setDesc(String desc)
{
this.desc = desc;
}
public boolean getIsVideo()
{
return isVideo;
}
public void setIsVideo(boolean isVideo)
{
this.isVideo = isVideo;
}
public boolean getIsDeleted()
{
return isDeleted;
}
public void setIsDeleted(boolean isDeleted)
{
this.isDeleted = isDeleted;
}
public String getUrlImg()
{
return urlImg;
}
public void setUrlImg(String urlImg)
{
this.urlImg = urlImg;
}
public String getUrlApp()
{
return urlApp;
}
public void setUrlApp(String urlApp)
{
this.urlApp = urlApp;
}
public int getUpdates()
{
return updates;
}
public void setUpdates(int updates)
{
this.updates = updates;
}
public boolean getIsDownloaded()
{
return isDownloaded;
}
public void setIsDownloaded(boolean isDownloaded)
{
this.isDownloaded = isDownloaded;
}
public String getLocation()
{
return location;
}
public void setLocation(String location)
{
this.location = location;
}
}
And I can successfully add objects to the database.
The problem comes when I need to update an object.
This is what I tried:
private void downloadUpdateDatabase(String uid,String location_address) throws RealmException
{
mRealm.beginTransaction();
ARDatabase db = new ARDatabase();
db.setUid(uid);
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");
}
The problem here is when I invoke this method. The mentioned fields get updated, but the not mentioned fields in this method become null or zero.
Of course I can set values for all fields by invoking their setters, however from where I invoke this method, I can't get all the field values.
So, the Question is: How do I update my realm database in such a way that the existing fields don't become null ?
P.S.:
My Realm version is :0.84.1, compile 'io.realm:realm-android:0.84.1'
the field that are mentioned gets updated, however the fields that are not mentioned in this method becomes null or zero
Well, yes, all fields are their defaults at this point.
ARDatabase db = new ARDatabase();
Have you tried to query for the current record, then update the fields, then put that object back?
In other words, you have String uid, so something like
private void downloadUpdateDatabase(String uid,String location_address) throws RealmException
{
mRealm.beginTransaction();
ARDatabase db = mRealm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
}
Or, probably better in async fashion.
private void downloadUpdateDatabase(final String uid, final String location_address) throws RealmException
{
mRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ARDatabase db = realm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
db.setIsDownloaded(true);
db.setLocation(location_address);
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
// Transaction was a success.
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
// Transaction failed and was automatically canceled.
}
});
}
Instead of
mRealm.beginTransaction();
ARDatabase db = new ARDatabase();
db.setUid(uid);
db.setIsDownloaded(true);
db.setLocation(location_address);
mRealm.copyToRealmOrUpdate(db);
mRealm.commitTransaction();
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");
There should be
mRealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
ARDatabase db = realm.where(ARDatabase.class).equalTo("uid", uid).findFirst();
if(db == null) {
db = realm.createObject(ARDatabase.class, uid);
}
db.setIsDownloaded(true);
db.setLocation(location_address);
}
});
Log.e("TAG","DOWNLOAD UPDATE COMPLETED");

Categories

Resources