com.google.firebase.database.DatabaseException:无法转换java.lang.String类型的对象

时间:2017-09-12 01:56:42

标签: android firebase firebase-realtime-database

我是一名自学的机器人。 这是我的第一个问题。请帮帮我。

09-12 01:35:35.723 2355-2355/com.example.jan.sanhakproject E/AndroidRuntime: 
FATAL EXCEPTION: main
                                                                                 Process: com.example.jan.sanhakproject, PID: 2355
                                                                                 com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.example.jan.sanhakproject.Chat
                                                                                     at com.google.android.gms.internal.zzbqi.zze(Unknown Source)
                                                                                     at com.google.android.gms.internal.zzbqi.zzb(Unknown Source)
                                                                                     at com.google.android.gms.internal.zzbqi.zza(Unknown Source)
                                                                                     at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
                                                                                     at com.example.jan.sanhakproject.ChatActivity$2.onChildAdded(ChatActivity.java:115)
                                                                                     at com.google.android.gms.internal.zzblz.zza(Unknown Source)
                                                                                     at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                                                     at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:154)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    09-12 01:35:44.318 2355-2374/com.example.jan.sanhakproject W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

Chat.java

公共课聊天{

    public String email;

    public String text;

    public Chat() {
        // Default constructor required for calls to DataSnapshot.getValue(Comment.class)
    }

    public Chat(String text) {

        this.text = text;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

ChatActivity.java

    public class ChatActivity extends AppCompatActivity {
    String TAG = this.getClass().getSimpleName();
    private DatabaseReference mDatabase;
    private FirebaseDatabase firebaseDatabase;
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    String[] myDataset = {"안녕", "오늘","뭐했어","영화볼래?"};
    DatabaseReference databaseReference;


    EditText etText;
    Button btnSend;
    String email;
    List<Chat> mChat;
    FirebaseDatabase database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        firebaseDatabase = FirebaseDatabase.getInstance();
        databaseReference = firebaseDatabase.getReference();

        //database = FirebaseDatabase.getInstance();
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {
            // Name, email address, and profile photo Url
            email = user.getEmail();
        }

        Intent in = getIntent();
        final String stChatId = in.getStringExtra("friendUid");

        etText = (EditText) findViewById(R.id.etText);
        btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String stText = etText.getText().toString();

                if (stText.equals("") || stText.isEmpty()) {
                    Toast.makeText(ChatActivity.this, "내용을 입력해 주세요.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(ChatActivity.this, email + "," + stText, Toast.LENGTH_SHORT).show();


                    Calendar c = Calendar.getInstance();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String formattedDate = df.format(c.getTime());


                    databaseReference = database.getReference("users").child(stChatId).child(formattedDate);

                    Hashtable<String, String> chat = new Hashtable<String, String>();
                    chat.put("email", email);
                    chat.put("text", stText);
                    databaseReference.setValue(chat);
                    etText.setText("");


                }


            }
        });


        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mChat = new ArrayList<>();
        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(mChat, email, ChatActivity.this);
        mRecyclerView.setAdapter(mAdapter);


        databaseReference.child("users").child(stChatId).child("chats").addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Chat chat = dataSnapshot.getValue(Chat.class);
                mChat.add(chat);


                mRecyclerView.scrollToPosition(mChat.size() - 1);
                mAdapter.notifyItemInserted(mChat.size() - 1);
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

}

MyAdapter.java

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private String[] mDataset;
    List<Chat> mChat;
    String stEmail;
    Context context;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder public static class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView mTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            mTextView = (TextView) itemView.findViewById(R.id.mTextView);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(List<Chat> mChat, String email, Context context) {
        this.mChat = mChat;
        this.stEmail = email;
        this.context = context;

    }

    @Override
    public int getItemViewType(int position) {

        if (mChat.get(position).getEmail().equals(stEmail)){
            return 1;
        } else {
            return 2;
        }
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        // create a new view
        View v;
        if (viewType == 1) {
            v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.right_text_view, parent, false);
        } else {
             v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.my_text_view, parent, false);
        }
        // set the view's size, margins, paddings and layout parameters
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.mTextView.setText(mChat.get(position).getText());
        holder.mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
            }
        });

    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mChat.size();
    }
}

1 个答案:

答案 0 :(得分:0)

异常日志表示代码正在尝试获取对象Chat的值并且正在查找String。错误发生在onChildAdded()的此语句中:

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

检查您的数据库以确认/users/stChatId/chats的所有子项都是有效的Chat个对象。看起来您正在寻找新的聊天:/users/stChatId/chats

databaseReference.child("users").child(stChatId).child("chats").addChildEventListener(...)

但是正在这个地方写聊天:

databaseReference = database.getReference("users").child(stChatId).child(formattedDate);