字符串空对象引用

时间:2019-07-06 18:29:38

标签: java android firebase-realtime-database nullpointerexception

我想在我的聊天应用程序中向我显示所有消息,但是每次我打开活动时,该应用程序都会崩溃。如果我删除 readMessage()上的if方法,它将向我显示消息,但是它会在每次用户聊天中向我显示针对不同用户的每条消息。我认为这不是最好的解决方案。我可以修改什么? 我的数据库看起来像this

我试图断言聊天!=空。

这是我的MessageAcitvity,其中有RecyclerView:

public class MessageActivity extends AppCompatActivity {
    TextView username;
    FirebaseUser fuser;
    DatabaseReference reference;
    Intent intent;
    ImageButton btn_send;
    EditText text_send;
    MessageAdapter messageAdapter;
    List<Chat> mchat;
    RecyclerView recyclerView;

    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate ( savedInstanceState );
        setContentView ( R.layout.activity_message );
        btn_send=findViewById ( R.id.btn_send );
        text_send=findViewById ( R.id.editText );
        recyclerView=findViewById ( R.id.recycler_view );
        recyclerView.setHasFixedSize ( true );
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager ( getApplicationContext () );
        linearLayoutManager.setStackFromEnd ( true );
        recyclerView.setLayoutManager ( linearLayoutManager );







            username=findViewById ( R.id.username6 );


            intent=getIntent ();
            final String userid=intent.getStringExtra ( "FIRST NAME " );
        fuser= FirebaseAuth.getInstance ().getCurrentUser ();
        reference= FirebaseDatabase.getInstance ().getReference ("users");
        reference.addValueEventListener ( new ValueEventListener () {
            @Override
            public void onDataChange (@NonNull DataSnapshot dataSnapshot) {



                for(DataSnapshot snapshot:dataSnapshot.getChildren ()){
                    User user=snapshot.getValue (User.class);


                    assert user!=null;
                    assert fuser!=null;
                    if(!fuser.getUid ().equals ( user.getFirstName () )){
                        username.setText ( user.getFirstName () );



                    }

                }
                readMessages ( fuser.getUid (),userid );

            }

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

            }
        } );
        btn_send.setOnClickListener ( new View.OnClickListener () {
            @Override
            public void onClick (View view) {
                String msg=text_send.getText ().toString ();
                if(!msg.equals ( "" )){
                    sendMessage ( fuser.getUid (),userid,msg );
                } else{
                    Toast.makeText ( MessageActivity.this,"You can't send empty",Toast.LENGTH_SHORT ).show ();
                }
                text_send.setText ( "" );
            }

        } );


        }
private void sendMessage(String sender,String receiver,String message)
{
    DatabaseReference reference=FirebaseDatabase.getInstance ().getReference ();
    HashMap<String,Object> hashMap=new HashMap<> (  );
    hashMap.put ( "sender",sender );
    hashMap.put ( "receiver",receiver );
    hashMap.put ( "message",message );
    reference.child ( "Chats" ).push ().setValue ( hashMap );
}
private void readMessages(final String myid, final String userid)
{
    mchat=new ArrayList<> (  );
    reference=FirebaseDatabase.getInstance ().getReference ("Chats");
    reference.addValueEventListener ( new ValueEventListener () {
        @Override
        public void onDataChange (@NonNull DataSnapshot dataSnapshot) {
            mchat.clear ();
            for(DataSnapshot snapshot:dataSnapshot.getChildren ()){
                Chat chat=snapshot.getValue (Chat.class);
                assert chat != null;
                if(chat.getReceiver ().equals ( myid )&& chat.getSender ().equals ( userid ) || chat.getReceiver ().equals ( userid )&& chat.getSender ().equals ( myid ))
                    mchat.add ( chat );
                messageAdapter=new MessageAdapter ( MessageActivity.this,mchat );
                recyclerView.setAdapter ( messageAdapter );
            }
        }

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

        }
    } );
}
    }


我的MessageAdapter类:

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
    public static final int MSG_TYPE_LEFT=0;
    public static  final int MSH_TYPE_RIGHT=1;
    private Context mContext;
    private List<Chat> mChat;
    FirebaseUser fuser;

    public MessageAdapter(Context mContext,List<Chat> mChat){
        this.mChat=mChat;
        this.mContext=mContext;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder (@NonNull ViewGroup parent, int viewType) {
        if(viewType==MSH_TYPE_RIGHT){
        View view= LayoutInflater.from ( mContext ).inflate ( R.layout.chat_item_right ,parent,false);

        return new MessageAdapter.ViewHolder ( view );
    }else{
            View view= LayoutInflater.from ( mContext ).inflate ( R.layout.chat_item_left ,parent,false);

            return new MessageAdapter.ViewHolder ( view );
        }
    }

    @Override
    public void onBindViewHolder (@NonNull ViewHolder holder, int position) {
Chat chat=mChat.get ( position );
holder.show_message.setText ( chat.getMessage () );


    }

    @Override
    public int getItemCount () {
        return mChat.size ();
    }

    public class ViewHolder extends RecyclerView.ViewHolder{

        public TextView show_message;

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

    }

    @Override
    public int getItemViewType (int position) {
        fuser= FirebaseAuth.getInstance ().getCurrentUser ();
        if(mChat.get ( position ).getSender ().equals ( fuser.getUid () )){
            return MSH_TYPE_RIGHT;
        }else
        {
            return MSG_TYPE_LEFT;
        }
    }
}

聊天类:

public class Chat {
    private String sender;
    private String receiver;
    private String message;

    public Chat (String sender, String receiver, String message) {
        this.sender = sender;
        this.receiver = receiver;
        this.message = message;
    }
    public Chat(){

    }

    public String getSender () {
        return sender;
    }

    public void setSender (String sender) {
        this.sender = sender;
    }

    public String getReceiver () {
        return receiver;
    }

    public void setReceiver (String receiver) {
        this.receiver = receiver;
    }

    public String getMessage () {
        return message;
    }

    public void setMessage (String message) {
        this.message = message;
    }
}

调试器向我显示:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.sportsbuddy, PID: 26180
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
        at com.example.sportsbuddy.MessageActivity$3.onDataChange(MessageActivity.java:134)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@17.0.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@17.0.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@17.0.0:55)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:6986)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)

我希望向我展示所有消息。

2 个答案:

答案 0 :(得分:0)

  • 尝试缓存错误,并在错误为null时予以抑制。
  • 检查行(.equals)
  • 创建本地变量并初始化默认值(类似于String myid = 0,userid =“ n / a”)
  • 从readMessage方法发出并单击侦听器-您的值为空
  • 记录值DataSnapShot并检查它

答案 1 :(得分:0)

错误消息显示:

  

试图在空对象引用上调用虚拟方法boolean java.lang.String.equals(java.lang.Object)

因此,您在某个地方呼叫something.equals(...),而somethingnull。堆栈跟踪告诉您问题所在:

  

MessageActivity $ 3.onDataChange(MessageActivity.java:134)

因此,在MessageActivity.java方法内的onDataChange的第134行。虽然我不确定第134行是什么,但是您共享的代码中只有一个onDataChange方法,那里只有一个对equals的调用:

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

            assert user!=null;
            assert fuser!=null;
            if(!fuser.getUid ().equals ( user.getFirstName () )){
                username.setText ( user.getFirstName () );
            }
        }
        readMessages ( fuser.getUid (),userid );
    }

所以问题似乎出在这一行:

if(!fuser.getUid().equals ( user.getFirstName () )){

具体来说:fuser.getUid()似乎返回null,这意味着您正在呼叫null.equals(...),这就是错误消息的意思。

FirebaseAuth.getInstance().getCurrentUser()返回一个用户对象,然后getUid()返回null的情况并不常见,但这似乎对您来说正在发生。