【问题标题】:how to solve this error: com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String如何解决此错误:com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String
【发布时间】:2021-10-09 10:43:07
【问题描述】:

我正在尝试从 Firebase 实时数据库中检索数据,我想在屏幕上以 TextView 显示它们,但我遇到了这个错误:

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)

ChatListFragment类的代码如下:

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();
      }
    }
}

ModelChatList 的代码如下:

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

我正在尝试在 Firebase 中显示此子节点的值,但由于此错误,我无法这样做。

【问题讨论】:

  • 错误是直截了当的,在第 67 行附近转换ds.getValue(ModelChatlist.class) 收到的字符串时出错。这里您尝试将String 分配给ModelChatlist 变量。您可能希望通过参数化构造函数(即ModelChatlist(String s))创建一个ModelChatlist 对象
  • 已经在modelchatlist @CcmU中创建
  • 所以ds.getValue 确实提供了id 值,对吗?
  • 你考虑过阅读剩下的信息吗?阅读“输入com.example.chocolate.ModelChatlist”的部分?
  • 不只考虑id的@user207421

标签: java android firebase firebase-realtime-database


【解决方案1】:

您收到以下错误:

com.google.firebase.database.DatabaseException:无法将 java.lang.String 类型的对象转换为 com.example.chocolate.ModelChatlist 类型

因为您试图将 String 类型的对象转换为 ModelChatlist 类型的对象,这在 Java 中实际上是不可能的。发生这种情况是因为您正在使用 getChildren() 方法循环遍历 DataSnapshot 对象。 UID 节点中的所有子节点都是字符串元素,而不是 ModelChatlist 对象,因此会出现该错误。

要解决这个问题,您必须删除循环:

  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!
      }
  });

【讨论】:

  • 嘿帕万。我可以帮助您了解其他信息吗?如果您认为我的回答对您有所帮助,请考虑通过单击左侧投票箭头下方的复选标记(✔️)来接受它。应将颜色更改为绿色。我真的很感激。谢谢!
【解决方案2】:

正如我在 cmets 中所说,尝试将 ds.getValue(ModelChatlist.class) 接收到的字符串转换为 ModelChatlist 变量时会发生错误。因为,我假设,ds.getValue() 提供了 idModelChatlist 值,你会想要做这样的事情:

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

【讨论】:

  • 在使用同样的错误@CcmU 之后
猜你喜欢
  • 2018-05-09
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-09
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多