You cannot convert an object of type java.lang.String to type com.mycare.OtherClass… here is a solution to the problem.
You cannot convert an object of type java.lang.String to type com.mycare.OtherClass
I’ve looked at some other answers to similar questions but don’t understand why my answer doesn’t work.
In my Firebase database, I have a list of users with different information underneath them. I want to retrieve information from the current userId to recyclerview.
My code is as follows:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference databaseStatus = rootRef.child("other");
String uid = firebaseAuth.getInstance().getCurrentUser().getUid();
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
OtherClass otherClass = dSnapshot.getValue(OtherClass.class);
Log.d("Show", otherClass.getOname() == null ? "" : otherClass.getOname());
list.add(otherClass);
}
adapter = new ShowOtherDetails.OtherAdapter(ShowOtherDetails.this, list);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}
This gives me this error :
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.mycare.OtherClass
The Firebase data structure is as follows:
Please, can someone help me?
Solution
Try this :
Do this when saving:
String key = databaseStatus.child(uid).push().getKey()
This way you can get the key.
Then add the
key as child when searching here in the first method
databaseStatus.child(uid).child(key).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
OtherClass otherClass = snapshot.getValue(OtherClass.class);
Log.d("Show", otherClass.getOname() == null ? "" : otherClass.getOname());
list.add(otherClass);
}
Remove the for loop for (DataSnapshot ds : snapshot.getChildren()).
Or do it like this:
databaseStatus.child(uid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
for (DataSnapshot dSnapshot : ds.getChildren()) {
String date=dataSnapshot.child("date").getValue().toString();
String detail=dataSnapshot.child("detail").getValue().toString();
String email=dataSnapshot.child("email").getValue().toString();
String id=dataSnapshot.child("id").getValue().toString()
and so on
}