本文介绍了字符串空对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want in my chat app to show me all the messages but every time i open the activity the app crashes.If i delete the if method on readMessage() it will show me the messages but it'll show me every message that i have for a different user in every user chat. I don't think it's the best solution. What I can modify ?My database looks like this

我试图断言聊天!=空.

I tried to asser chat!=null.

这是我的MessageAcitvity,其中有RecyclerView:

Here is My MessageAcitvity where i have the 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类:

My MessageAdapter class :

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)

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

I expect to show me all the messages.

推荐答案

错误消息显示:

所以您在某处调用something.equals(...),而somethingnull.堆栈跟踪告诉您问题所在:

So you're calling something.equals(...) somewhere, and something is null. The stack trace tells you that the problem is on:

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

So on line 134 of MessageActivity.java, inside the onDataChange method. While I can't be certain what line 134 is, there is only one onDataChange method in the code you shared, and only one call to equals in there:

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

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

So the problem seems to come from this line:

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

具体来说:fuser.getUid()似乎返回null,这意味着您正在调用null.equals(...),这就是错误消息所显示的内容.

Specifically: fuser.getUid() seems to return null, which means you're calling null.equals(...) and that's what the error message says.

FirebaseAuth.getInstance().getCurrentUser()返回用户对象,然后getUid()返回null的情况并不常见,但这确实是您正在发生的事情.

It's fairly uncommon for FirebaseAuth.getInstance().getCurrentUser() to return a user object, and then for getUid() to return null, but that does seem to be what's happening for you.

这篇关于字符串空对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:04