FirebaseRecyclerAdapter的popuplateViewHolder如何在不抓取空模型的情况下创建一个合适的模型类?

时间:2017-06-26 02:21:55

标签: android firebase firebase-realtime-database recycler-adapter

因此,每当我的适配器尝试创建聊天项时,它总是提供

  

错误:java.lang.NullPointerException:尝试调用虚拟   null上的方法'boolean java.lang.String.equals(java.lang.Object)'   对象参考   com.swampass.nauticalapp.ChatConversationActivity $ 2.populateViewHolder(ChatConversationActivity.java:178)

活动的这一部分:

if(mSender.equals(HomeActivity.LoggedIn_User_Email)){...}

我不确定为什么会这样做,因为我对它如何实际抓取类不太熟悉,但是当我点击发送时数据库正在使用消息进行更新。我尝试了不同的东西,但似乎无法找到解决方法。

这是聊天的地方:

公共类ChatConversationActivity扩展了AppCompatActivity {

    DatabaseReference myRef,myRef2,chatRef,userRef;
    ImageView attach_icon,send_icon,no_data_available_image;
    EditText message_area;
    TextView no_chat;
    public LinearLayoutManager mLinearLayoutManager;
    static String Sender_Name;
    public RecyclerView recyclerView;
    //ChatItemAdapter adapter;
    ArrayList<ChatMessage> msgs;
    private FirebaseRecyclerAdapter<ChatMessage,ViewHolder> mUserMsg;

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

        final String USER_ID = HomeActivity.LoggedIn_User_Email.replace("@","").replace(".","");
        String email= getIntent().getStringExtra("descripion").replace("@","").replace(".","");
        myRef = FirebaseDatabase.getInstance().getReference().child("Chat").child(USER_ID).child(email);
        myRef.keepSynced(true);
        //Log.d("LOGGED", "myRef : " + myRef);



        myRef2 = FirebaseDatabase.getInstance().getReference().child("Chat").child(getIntent().getStringExtra("descripion").replace("@","").replace(".","")).child(USER_ID);
        myRef2.keepSynced(true);

        chatRef = FirebaseDatabase.getInstance().getReference().child("Chat");
        userRef = FirebaseDatabase.getInstance().getReference().child("Users");
        //Log.d("LOGGED", "myRef2 : " + myRef2);


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle(getIntent().getStringExtra("name") + "</font>");
        }

        Sender_Name = getIntent().getStringExtra("name");

        attach_icon = (ImageView)findViewById(R.id.attachButton);
        send_icon = (ImageView)findViewById(R.id.sendButton);
        no_data_available_image = (ImageView)findViewById(R.id.no_data_available_image);
        message_area = (EditText)findViewById(R.id.messageArea);
        no_chat = (TextView)findViewById(R.id.no_chat_text);

        msgs= new ArrayList<>();
        //adapter = new ChatItemAdapter(msgs,this,myRef2);

        recyclerView = (RecyclerView)findViewById(R.id.chat_recycler_view);
        mLinearLayoutManager = new LinearLayoutManager(ChatConversationActivity.this);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        mLinearLayoutManager.setStackFromEnd(true);


        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);

        send_icon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = message_area.getText().toString().trim();

                if(!messageText.equals("")){

                    //Date dick = DateFormat.getDateInstance().getCalendar().getTime();
                    ChatMessage msg = new ChatMessage(messageText, USER_ID);
                    final DatabaseReference pushRef = chatRef.push();
                    final String pushKey = pushRef.getKey();



                   // ArrayMap<String, String> map = new ArrayMap<>();
                  //  map.put("message", messageText);
                 //   map.put("sender", HomeActivity.LoggedIn_User_Email);
                    //myRef.push().setValue(map);
                   // myRef2.push().setValue(map);

                    HashMap<String, Object> messageItemMap = new HashMap<String, Object>();
                    HashMap<String,Object> messageObj = (HashMap<String, Object>) new ObjectMapper().convertValue(msg, Map.class);
                    messageItemMap.put(pushKey, messageObj);

                    chatRef.push().setValue(messageItemMap);

                    msgs.add(msg);

                    message_area.setText("");


                }

            }

        });


        mUserMsg = new FirebaseRecyclerAdapter<ChatMessage, ViewHolder>(ChatMessage.class,R.layout.chat_item,ViewHolder.class,chatRef.getRef()) {
            @Override
            protected void populateViewHolder(ViewHolder view, ChatMessage message, int position) {
                LinearLayout messageLine = view.layout;
                TextView messgaeText = view.message;
                TextView senderText = view.sender;
                //TextView timeTextView = (TextView) view.findViewById(R.id.timeTextView);
                final ImageView leftImage = view.leftPic;
                final ImageView rightImage = view.rightPic;
                LinearLayout individMessageLayout = view.messageLayout;

                //set message and sender text
                messgaeText.setText(message.getMessageText());
                senderText.setText(message.getUserID());
                //If you sent this message, right align
                String mSender = message.getUserID();

                if(mSender.equals(HomeActivity.LoggedIn_User_Email)){
                    //messgaeText.setGravity(Gravity.RIGHT);
                    //senderText.setGravity(Gravity.RIGHT);
                    messageLine.setGravity(Gravity.RIGHT);
                    leftImage.setVisibility(View.GONE);
                    rightImage.setVisibility(View.VISIBLE);

                    individMessageLayout.setBackgroundResource(R.drawable.incoming_msg);
                    //messgaeText.setBackgroundColor(ResourcesCompat.getColor(getResources(),
                    //       R.color.colorAccent, null));
                }else if(mSender.equals("System")){
                    messageLine.setGravity(Gravity.CENTER_HORIZONTAL);
                    leftImage.setVisibility(View.GONE);
                    rightImage.setVisibility(View.GONE);
                }else{
                    //messgaeText.setGravity(Gravity.LEFT);
                    //senderText.setGravity(Gravity.LEFT);
                    messageLine.setGravity(Gravity.LEFT);
                    leftImage.setVisibility(View.VISIBLE);
                    rightImage.setVisibility(View.GONE);
                    individMessageLayout.setBackgroundResource(R.drawable.round_corners);
                    //messgaeText.setBackgroundColor(ResourcesCompat.getColor(getResources(),
                    //       R.color.colorPrimary, null));



                }

            }
        };
        recyclerView.setAdapter(mUserMsg);
    }




    public static class ViewHolder extends RecyclerView.ViewHolder  {
        private final TextView message, sender;
        private final ImageView leftPic,rightPic;
        private final LinearLayout.LayoutParams params, text_params;
        LinearLayout layout,messageLayout;


        public ViewHolder(final View itemView) {
            super(itemView);

            message = (TextView) itemView.findViewById(R.id.messageTextView);
            sender = (TextView) itemView.findViewById(R.id.senderTextView);
            //date = (TextView) itemView.findViewById(R.id.date_txt);
            text_params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);;
            layout = (LinearLayout) itemView.findViewById(R.id.messageLine);
            leftPic = (ImageView) itemView.findViewById(R.id.leftMessagePic);
            rightPic = (ImageView) itemView.findViewById(R.id.rightMessagePic);
            messageLayout = (LinearLayout)itemView.findViewById(R.id.individMessageLayout);
        }

    }

}

这是我的聊天消息模型:

package com.swampass.nauticalapp.model;

import java.util.Date;

public class ChatMessage {

    private String messageText;
    private String userID;
   // private Date date;


    public ChatMessage()
    {

    }

    //plain text message
    public ChatMessage(String messageText, String userID) {
        this.messageText = messageText;
        this.userID = userID;
    }



    public String getUserID() {return userID;}


    public void setMessageText(String messageText) {this.messageText = messageText;}
    public String getMessageText() { return messageText;}


}

以下是数据库中的内容:enter image description here

1 个答案:

答案 0 :(得分:1)

这种情况正在发生,因为您正在使用String类foo中的equals()方法。这意味着on a null object reference为空。要解决此问题,您需要确保已登录的用户HomeActivity.LoggedIn_User_Email。首先尝试用真实的电子邮件地址替换is not null以查看代码是否有效,然后调试代码以获得正确的登录用户。

还有一件事,您不需要替换HomeActivity.LoggedIn_User_Email符号,只需要@(点)符号才能正确使用电子邮件地址。

希望它有所帮助。