无法将java.lang.String类型的对象转换为In DatabaseReferance类型

时间:2018-11-05 14:54:07

标签: java android android-studio

我正在构建一个简单的聊天应用程序。在用户片段中,如果我们单击用户,则会崩溃,如果有以前的聊天,请转到上一个活动。虽然没有与该用户片段进行聊天的情况很好,但是当我们在Firebase上键入消息并单击“发送消息存储”并且应用程序崩溃时,类似地,如果存在聊天,聊天片段也会崩溃。

我认为问题出在mReference.addValueEventListener(new ValueEventListener())方法中。代码和错误在下面给出。我看到了其他答案,但对我的代码不理解。

MessageActivity.java

public class MessageActivity extends AppCompatActivity {

    CircleImageView profile_image;
    TextView username;

    FirebaseUser mFirebaseUser;
    DatabaseReference mDatabaseReference;

    ImageView btn_send;
    EditText send_msg;

    Intent mIntent;
    MessageAdapter mMessageAdapter;
    List<Chat> mChats;
    RecyclerView mRecyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        profile_image = findViewById(R.id.profile_image);
        username = findViewById(R.id.username);
        btn_send = findViewById(R.id.img_btn_send);
        send_msg = findViewById(R.id.text_send);

        mRecyclerView = findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        linearLayoutManager.setStackFromEnd(true);
        mRecyclerView.setLayoutManager(linearLayoutManager);

        mIntent = getIntent();

        final String userid = mIntent.getStringExtra("userid");

        mFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        mDatabaseReference = FirebaseDatabase.getInstance().getReference("Users").child(userid);

        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = send_msg.getText().toString();
                if (!msg.equals("")){
                    sendMessage(mFirebaseUser.getUid(), userid, msg);
                }
                send_msg.setText("");
            }
        });

        mDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                User user = dataSnapshot.getValue(User.class);
                assert user != null;
                username.setText(user.getUsername());
                if ( user.getImageURL().equals("default")){
                    profile_image.setImageResource(R.mipmap.ic_launcher_round);
                }else {
                    Glide.with(MessageActivity.this).load(user.getImageURL()).into(profile_image);
                }

                readMessage(mFirebaseUser.getUid(), userid, user.getImageURL());
            }

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

            }
        });
    }

    private void sendMessage(String sender, String receiver, String message){
        DatabaseReference mDatabaseReference = FirebaseDatabase.getInstance().getReference();

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("sender", sender);
        hashMap.put("receiver", receiver);
        hashMap.put("message", message);

        mDatabaseReference.child("Chats").setValue(hashMap);
    }

    private void readMessage(final String myId, final String userID, final String imageURL){
        mChats = new ArrayList<>();

        mDatabaseReference = FirebaseDatabase.getInstance().getReference("Chats");
        mDatabaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mChats.clear();
                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){

                    Chat chat = dataSnapshot1.getValue(Chat.class);

                    assert chat != null;
                    if (chat.getReceiver().equals(myId) && chat.getSender().equals(userID) || chat.getReceiver().equals(userID) && chat.getSender().equals(myId)){
                        mChats.add(chat);
                    }

                    mMessageAdapter = new MessageAdapter(MessageActivity.this, mChats, imageURL);
                    mRecyclerView.setAdapter(mMessageAdapter);
                }
            }

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

            }
        });
    }
}

ChatsFragment.java

public class ChatsFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private UserAdapter mUserAdapter;
    private List<User> mUsers;

    FirebaseUser fUser;
    DatabaseReference mReference;

    private List<String> userList;

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

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

        mRecyclerView = view.findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        fUser = FirebaseAuth.getInstance().getCurrentUser();

        userList = new ArrayList<>();

        mReference = FirebaseDatabase.getInstance().getReference("Chats");
        mReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                userList.clear();
                for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                    Chat chat = snapshot.getValue(Chat.class);

                    if (chat.getSender().equals(fUser.getUid())){
                        userList.add(chat.getReceiver());
                    }
                    if (chat.getReceiver().equals(fUser.getUid())){
                        userList.add(chat.getSender());
                    }
                }

                readChats();
            }

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

            }
        });

        return view;
    }

    private void readChats() {

        mUsers = new ArrayList<>();

        mReference = FirebaseDatabase.getInstance().getReference("Users");

        mReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mUsers.clear();
                for (DataSnapshot snapshot: dataSnapshot.getChildren()){
                   User user = snapshot.getValue(User.class);

                    for (String id : userList){
                        if (user.getId().equals(id)){
                            if (mUsers.size() != 0){
                                for ( User user1 : mUsers){
                                    if ( !user.getId().equals(user1.getId()));
                                    mUsers.add(user);
                                }
                            }
                            else{
                                mUsers.add(user);

                            }
                        }
                    }
                }

                mUserAdapter = new UserAdapter(getContext(), mUsers);
                mRecyclerView.setAdapter(mUserAdapter);
            }

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

            }
        });
    }

}

错误是:

com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type 
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(com.google.firebase:firebase-database@@16.0.4:423)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(com.google.firebase:firebase-database@@16.0.4:214)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(com.google.firebase:firebase-database@@16.0.4:79)
        at com.google.firebase.database.DataSnapshot.getValue(com.google.firebase:firebase-database@@16.0.4:212)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@16.0.4:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@16.0.4:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@16.0.4:55)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6228)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)

0 个答案:

没有答案