空指针异常,因为添加了通知

时间:2018-11-20 22:31:50

标签: android firebase firebase-realtime-database firebase-authentication

当我运行该应用程序时,我没有收到错误消息,但一切正常,但是当我单击“发送消息”按钮时,该应用程序崩溃了,但消息仍然被发送。下面是我的chatActivity和logcat消息的代码

package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{

    private String messageReceiverId;
    private  String messageReceiverName;

   // private Toolbar ChatToolBar;

    private TextView userNameTitle;
    private TextView userLastSeen;
    private CircleImageView userChatProfileImage;


    private ImageButton SendMessageButton;
   // private ImageButton SelectImageButton;
    private EditText InputMessageText;


    FirebaseUser fuser;
    DatabaseReference rootRef;

    private FirebaseAuth mAuth;
    private String messageSenderId;


    private RecyclerView userMessagesList;
    private final List<Messages> messageList = new ArrayList<>();

    private LinearLayoutManager linearLayoutManager;

    private MessageAdapter messageAdapter;

    private static int Gallery_Pick = 1;
    private StorageReference MessageImageStorageRef;
    private ProgressDialog loadingBar;
    private String downloadImageUrl;




    Intent intent;

    ValueEventListener seenListener;

    String userid;

    APIServiceFragment apiService;

    boolean notify = false;


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


        rootRef = FirebaseDatabase.getInstance().getReference();

        mAuth = FirebaseAuth.getInstance();
        messageSenderId = mAuth.getCurrentUser().getUid();



        messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
        messageReceiverName = getIntent().getExtras().get("user_name").toString();
        MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");



        apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);

      //  ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
//        setSupportActionBar(ChatToolBar);


        loadingBar = new ProgressDialog(this);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowCustomEnabled(true);

        LayoutInflater layoutInflater = (LayoutInflater)
                this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);

        actionBar.setCustomView(action_bar_view);

        userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
        userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
        userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);


        SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
       // SelectImageButton = (ImageButton) findViewById(R.id.select_image);
        InputMessageText = (EditText) findViewById(R.id.input_message);


        messageAdapter = new MessageAdapter(messageList);

        userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);

        linearLayoutManager = new LinearLayoutManager(this);

        userMessagesList.setHasFixedSize(true);

        userMessagesList.setLayoutManager(linearLayoutManager);

        userMessagesList.setAdapter(messageAdapter);




        FetchMessages();


        userNameTitle.setText(messageReceiverName);

        rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot)
            {
                final String online = dataSnapshot.child("online").getValue().toString();
                final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();


                Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
                        .into(userChatProfileImage, new Callback() {
                            @Override
                            public void onSuccess()
                            {

                            }

                            @Override
                            public void onError()
                            {
                                Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
                            }
                        });


                if (online != null) {
                    if (online.equals("true"))
                    {
                        userLastSeen.setText("online");
                    }

                    else
                    {
                        LastSeenTime getTime = new LastSeenTime();

                        long last_seen = Long.parseLong(online);

                        //problem with last seen time here

                        String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();


                        userLastSeen.setText(lastSeenDisplayTime);
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError)
            {

            }
        });



        SendMessageButton.setOnClickListener(new View.OnClickListener()
        {

            @Override
            public void onClick(View view)
            {
                SendMessage();
            }
        });



       // SelectImageButton.setOnClickListener(new View.OnClickListener() {
      //      @Override
        //    public void onClick(View v)
          //  {

            //    Intent galleryIntent = new Intent();
              //  galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
              //  galleryIntent.setType("image/*");
              //  startActivityForResult(galleryIntent, Gallery_Pick);
            //}
        //});


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
        {
            loadingBar.setTitle("Sending Image");
            loadingBar.setMessage("Please Wait");
            loadingBar.show();


            Uri ImageUri = data.getData();

            final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
            final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



            DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
                    .child(messageReceiverId).push();

            final String message_push_id = user_message_key.getKey();


            final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");

            final StorageTask<UploadTask.TaskSnapshot>  taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()) {

                        downloadImageUrl = filePath.getDownloadUrl().toString();
                      //  return filePath.getDownloadUrl();


                        Map messageTextBody = new HashMap();


                        messageTextBody.put("message", downloadImageUrl);
                        messageTextBody.put("isseen", true);
                        messageTextBody.put("type", "image");
                        messageTextBody.put("time", ServerValue.TIMESTAMP);
                        messageTextBody.put("from", messageSenderId);
                        messageTextBody.put("to", messageReceiverId);

                        Map messageBodyDetails = new HashMap();

                        messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
                        messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


                        rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                if (databaseError != null) {
                                    Log.d("Chat_Log", databaseError.getMessage().toString());
                                }

                                InputMessageText.setText("");

                                loadingBar.dismiss();
                            }
                        });


                        Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    } else {
                        Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }
            });
        }
    }

    private void FetchMessages()
    {

                rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
                        .addChildEventListener(new ChildEventListener() {
                            @Override
                            public void onChildAdded(DataSnapshot dataSnapshot, String s)
                            {

                                if (dataSnapshot.exists())
                                {
                                    Messages messages = dataSnapshot.getValue(Messages.class);

                                    messageList.add(messages);

                                    messageAdapter.notifyDataSetChanged();
                                    userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
                                }
                            }

                            @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)
                            {

                            }
                        });


              // seenMessage(userid);

    }



    private void seenMessage(final String userid) //add String and userid
    {
        rootRef = FirebaseDatabase.getInstance().getReference("Messages");
        seenListener = rootRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                for (DataSnapshot snapshot : dataSnapshot.getChildren())
                {
                    Messages messages = snapshot.getValue(Messages.class);

                    if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
                    {
                        Map messageTextBody = new HashMap();

                        messageTextBody.put("isseen", true);
                        snapshot.getRef().updateChildren(messageTextBody);

                    }
                }
            }

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

            }
        });
    }





    private void SendMessage()
    {


        notify = true;
                String messageText = InputMessageText.getText().toString();

                if (TextUtils.isEmpty(messageText))
                {
                    Toast.makeText(ChatActivity.this,
                            "Input message", Toast.LENGTH_SHORT).show();
                }

                else
                {
                    String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;

                    final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



                    DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
                            .child(messageReceiverId).push();

                    String message_push_id = user_message_key.getKey();


                    Map messageTextBody = new HashMap();


                    messageTextBody.put("message", messageText);
                    messageTextBody.put("isseen", false);
                    messageTextBody.put("type", "text");
                    messageTextBody.put("time", ServerValue.TIMESTAMP);
                    messageTextBody.put("from", messageSenderId);
                    messageTextBody.put("to", messageReceiverId);

                    Map messageBodyDetails = new HashMap();

                    messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);

                    messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


                    rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
                        @Override
                        public void onComplete(@NonNull Task task)
                        {
                         if (task.isSuccessful())
                         {
                             Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
                             InputMessageText.setText("");
                         }

                         else
                         {
                             String message = task.getException().getMessage();
                             Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
                             InputMessageText.setText("");
                         }




                        }
                    });





**i tried sending chat notification with the code below

这就是引发错误的原因,该错误仍然会发送消息,但应用程序崩溃并自行重启。**

                    final String msg = messageText;

                    rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
                    rootRef.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                        {
                         User user = dataSnapshot.getValue(User.class);
                         if (notify) {
                             sendNotification(message_receiver_ref, user.getUsername(), msg);
                                     }
                            notify = false;
                        }

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

                        }
                    });


                }

    }

    private void sendNotification(String message_receiver_ref, final String username, final String message)
    {
        DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
        Query query = tokens.orderByKey().equalTo(message_receiver_ref);
        query.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                for (DataSnapshot snapshot: dataSnapshot.getChildren())
                {
                    Token token = snapshot.getValue(Token.class);
                    Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
                            userid);

                    Sender sender = new Sender(data, token.getToken());

                    apiService.sendNotification(sender)
                            .enqueue(new retrofit2.Callback<MyResponse>() {
                                @Override
                                public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
                                {
                                    if (response.code() == 200)
                                    {
                                        if (response.body().success != 1)

                                        {
                                            Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(Call<MyResponse> call, Throwable t)
                                {

                                }
                            });
                }
            }

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

            }
        });
    }


}

这是下面的日志

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
        at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
        at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
        at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
        at android.view.View.performClick(View.java:5274)
        at android.view.View$PerformClick.run(View.java:21543)
        at android.os.Handler.handleCallback(Handler.java:815)
        at android.os.Handler.dispatchMessage(Handler.java:104)
        at android.os.Looper.loop(Looper.java:207)
        at android.app.ActivityThread.main(ActivityThread.java:5765)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

1 个答案:

答案 0 :(得分:0)

您遇到以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference

因为您的fuser对象未初始化。要解决此问题,请在您的onCreate()方法中添加以下代码行:

fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();