Home > Enterprise >  how to solve this error: com.google.firebase.database.DatabaseException: Can't convert object o
how to solve this error: com.google.firebase.database.DatabaseException: Can't convert object o

Time:10-10

I am trying to retrieve data from the Firebase Realtime Database and I want to display them on the screen in a TextView, but I'm facing whit this error:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.chocolate.ModelChatlist
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
            at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
            at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
            at com.example.chocolate.ChatListFragment$1.onDataChange(ChatListFragment.java:67)
            at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
            at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
            at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
            at android.os.Handler.handleCallback(Handler.java:938)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:233)
            at android.app.ActivityThread.main(ActivityThread.java:8010)
            at java.lang.reflect.Method.invoke(Native Method)

The code of ChatListFragment class is given below:

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.MenuItemCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class ChatListFragment extends Fragment {

  FirebaseAuth firebaseAuth;
  RecyclerView recyclerView;
  List<ModelChatlist> chatlistList;
  List<ModelUser> userList;
  DatabaseReference reference;
  FirebaseUser currentUser;
  AdapterChatlist adapterChatlist;

  public ChatListFragment(){
      //required empty
  }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      View view = inflater.inflate(R.layout.fragment_chat_list, container, false);

      firebaseAuth = FirebaseAuth.getInstance();
      currentUser = FirebaseAuth.getInstance().getCurrentUser();

      recyclerView = view.findViewById(R.id.recyclerView);

      chatlistList = new ArrayList<>();

      reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(currentUser.getUid());
      reference.addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
              chatlistList.clear();
             for (DataSnapshot ds: dataSnapshot.getChildren()) {
                 ModelChatlist chatlist = ds.getValue(ModelChatlist.class);
                 chatlistList.add(chatlist);
             }
              loadChats();
          }

          @Override
          public void onCancelled(@NonNull DatabaseError databaseError) {

          }
      });

        return view;
    }

    private void loadChats() {
      userList = new ArrayList<>();
      reference = FirebaseDatabase.getInstance().getReference("Users");
      reference.addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
              userList.clear();
              for (DataSnapshot ds: dataSnapshot.getChildren()) {
                  ModelUser user = ds.getValue(ModelUser.class);
                  for (ModelChatlist chatlist: chatlistList){
                      if (user.getUid() != null && user.getUid().equals(chatlist.getId())) {
                          userList.add(user);
                          break;
                      }
                  }
                  adapterChatlist = new AdapterChatlist(getContext(), userList);
                  recyclerView.setAdapter(adapterChatlist);
                  for (int i=0; i<userList.size(); i   ) {
                      lastMessage(userList.get(i).getUid());
                  }
              }
          }

          @Override
          public void onCancelled(@NonNull DatabaseError databaseError) {

          }
      });
    }

    private void lastMessage(String userId) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Chats");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                String theLastMessage = "default";
                for (DataSnapshot ds: dataSnapshot.getChildren()) {
                    ModelChat chat = ds.getValue(ModelChat.class);
                    if (chat==null) {
                        continue;
                    }
                    String sender = chat.getSender();
                    String receiver = chat.getReceiver();
                    if (sender == null || receiver == null) {
                        continue;
                    }
                    if (chat.getReceiver().equals(currentUser.getUid()) &&
                            chat.getSender().equals(userId) ||
                            chat.getReceiver().equals(userId) &&
                                    chat.getSender().equals(currentUser.getUid())){
                        theLastMessage = chat.getMessage();
                    }
                }
                adapterChatlist.setLastMessageMap(userId, theLastMessage);
                adapterChatlist.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

    private void checkUserStatus(){

      FirebaseUser user = firebaseAuth.getCurrentUser();
      if (user != null) {

      }
      else {
          startActivity(new Intent(getActivity(), MainActivity.class));
          getActivity().finish();
      }
    }
}

The code for ModelChatList is given below:

package com.example.chocolate;

public class ModelChatlist {
    String id;

    public ModelChatlist(String id) {
        this.id = id;
    }

    public ModelChatlist() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}

database Database

I am trying to display the value of this child node in the Firebase but I am unable to do so because of this error.

CodePudding user response:

You are getting the following error:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.chocolate.ModelChatlist

Because you are trying to convert an object of type String to an object of type ModelChatlist, which is actually not possible in Java. This is happening because you are looping through the DataSnapshot object using the getChildren() method. All children within the UID node, are String elements and not ModelChatlist objects, hence that error.

To solve this, you have to remove the loop:

  reference = FirebaseDatabase.getInstance().getReference("Chatlist").child(currentUser.getUid());
  reference.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
          chatlistList.clear();
          ModelChatlist chatlist = dataSnapshot.getValue(ModelChatlist.class);
          chatlistList.add(chatlist);
          loadChats();
      }

      @Override
      public void onCancelled(@NonNull DatabaseError databaseError) {
          Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
      }
  });

CodePudding user response:

As I said in the comments, the error occurs when trying to convert the string received by ds.getValue(ModelChatlist.class) into a ModelChatlist variable. Since, I assume, ds.getValue() provides the id value of a ModelChatlist, you'd want to do something like:

for (DataSnapshot ds: dataSnapshot.getChildren()) {
    ModelChatlist chatlist = new ModelChatlist (ds.getValue(ModelChatlist.class));
    chatlistList.add(chatlist);
}
  • Related