同时向位于同一数据库的用户发送消息

时间:2018-02-12 04:53:27

标签: java android firebase-realtime-database simultaneous-calls

我一直试图通过点击按钮(mRescue)在我的数据库(Emergency_Contact)中发送自定义消息,当点击按钮时,它将检查按下按钮的人的user_id为每个Emergency_Contact作为孩子的人签入senders_user_id,如果他们的孩子有sender_user_id,则会向他们发送消息,否则会返回Toast消息。我试图运行我的代码,但它崩溃我不知道为什么。 这是我执行此操作的活动。

 public class MenuActivity extends AppCompatActivity
 {

Button mRescue;

private  Double lati;
private GoogleMap mMap;
LocationManager locationManager;

private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String mChatUser;
private DatabaseReference mNotificationDatabase;

private String message;
private String value_lat = null;
private String value_long = null;

private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
LocationTrack locationTrack;

private DatabaseReference usersDatabase;
private DatabaseReference emergencyContactDB;

private String user_id;

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

    FirebaseApp.initializeApp(this);
    usersDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
    emergencyContactDB = FirebaseDatabase.getInstance().getReference().child("Emergency_Contact");
    mNotificationDatabase = FirebaseDatabase.getInstance().getReference().child("Emergency_Notifications");
    mRootRef = FirebaseDatabase.getInstance().getReference();
    mLocationDatabase = mRootRef.child("EmergencyMessages");
    mAuth = FirebaseAuth.getInstance();


    gettingIntent();




    mRescue = (Button)findViewById(R.id.rescue);
    mRescue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view)
        {
            if(value_lat == null & value_long == null)
            {
                mRescue.setEnabled(false);

            }
            else
            {
                mRescue.setEnabled(true);
                usersDatabase.addValueEventListener(new ValueEventListener()
                {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot)
                    {
                        final String user_db = dataSnapshot.child("user_id").getValue().toString();
                        if (!user_db.isEmpty())
                        {
                            user_id = dataSnapshot.child("user_id").getValue().toString();
                            emergencyContactDB.addValueEventListener(new ValueEventListener()
                            {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot)
                                {
                                    final String emergency_db = dataSnapshot.child(user_id).getValue().toString();
                                    if (emergency_db.contains(mCurrentUserId))
                                    {

                                        addEmergencyMessage();
                                        addEmergencyChat();
                                        Toast.makeText(getApplicationContext(), "Emergency Alert message was successfully sent",Toast.LENGTH_LONG).show();


                                    } else
                                    {

                                        Toast.makeText(getApplicationContext(), "You Do not have any emergency contacts. Please add them and try again.",Toast.LENGTH_LONG).show();
                                    }

                                }

                                @Override
                                public void onCancelled(DatabaseError databaseError) {

                                }
                            });

                        }
                        else {

                            Toast.makeText(getApplicationContext(), "The Database is Empty",Toast.LENGTH_LONG).show();
                        }

                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });


            }




        }
    });


    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Alerts");
    toolbar.setTitleTextColor(android.graphics.Color.WHITE);

    if (mAuth.getCurrentUser() != null) {


        mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
        mUserRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                userName = dataSnapshot.child("name").getValue().toString();


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

    }



private void checkUser() {

    if (mCurrentUserId == null) {
        sendToStart();
    }else{
        mUserRef.child("online").setValue("true");
    }
}

private void gettingIntent() {

    Intent intent =getIntent();
    mChatUser = intent.getStringExtra("user_id");
}



private void addEmergencyChat() {


    value_lat = String.valueOf(mLastLocation.getLatitude());
    value_long = String.valueOf(mLastLocation.getLongitude());
            String current_user_ref="Emergency_Messages/"+mCurrentUserId+"/"+user_id;
            String chat_user_ref= "Emergency_Messages/"+user_id+"/"+mCurrentUserId;

            DatabaseReference chat_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();

            String push_key = chat_push_key.getKey();

            Map messageMap = new HashMap();
            messageMap.put("userName", userName + " is in trouble on this location:"+"\nlatitude ="+value_lat +"\nlongitude ="+ value_long);
            messageMap.put("open_location", "Tap Here to see "+userName+"'s location");
            messageMap.put("type","text");
            messageMap.put("latitude",value_lat);
            messageMap.put("longitude", value_long);
            messageMap.put("from",mCurrentUserId);
            messageMap.put("seen",false);
            messageMap.put("time", ServerValue.TIMESTAMP);

    DatabaseReference newNotificationref = mRootRef.child("Emergency_Notifications").child(user_id).push();
    String newNotificationId = newNotificationref.getKey();

    HashMap<String, String> notificationData = new HashMap<>();
    notificationData.put("from", mCurrentUserId);
    notificationData.put("type", "alert");

    Map messageNotifMap = new HashMap();
    messageNotifMap.put("Emergency_Notifications/" + user_id + "/" + newNotificationId, notificationData);

            Map messageUserMap = new HashMap();
            messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
            messageUserMap.put(chat_user_ref+ "/"+push_key,messageMap);

            mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
                @Override
                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                    if(databaseError!=null){
                        Log.d("TAG",databaseError.getMessage().toString());
                    }
                }
            });

    }



private void addEmergencyMessage() {

    mRootRef.child("Emergency_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if(!dataSnapshot.hasChild(user_id)){

                Map chatAddMap = new HashMap();
                chatAddMap.put("seen",false);
                chatAddMap.put("timestamp", ServerValue.TIMESTAMP);

                Map chatUserMap = new HashMap();
                chatUserMap.put("Emergency_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
                chatUserMap.put("Emergency_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);

                mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
                    @Override
                    public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {

                        if(databaseError!= null){
                            Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();

                        }
                    }
                });
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}


@Override
public void onStart() {
    super.onStart();
    // Check if user is signed in (non-null) and update UI accordingly.

    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser == null){

        sendToStart();

    } else{
        mCurrentUserId = mAuth.getCurrentUser().getUid();
        mUserRef.child("online").setValue("true");

    }

}


@Override
protected void onStop() {
    super.onStop();



    FirebaseUser currentUser = mAuth.getCurrentUser();

    if(currentUser != null) {

        mUserRef.child("online").setValue(ServerValue.TIMESTAMP);

    }

}

private void sendToStart() {

    Intent startIntent = new Intent(MenuActivity.this, Home.class);
    startActivity(startIntent);
    finish();

}
}

我该如何发送此消息?

这是我的logcat

    02-12 07:01:23.046 32377-32377/? E/Zygote: no v2
   02-12 07:01:23.056 32377-32377/? E/SELinux: [DEBUG] get_category: 
 variable seinfo: default sensitivity: NULL, cateogry: NULL
02-12 07:01:34.477 32377-32377/com.rescuex_za.rescuex E/AndroidRuntime: 
 FATAL EXCEPTION: main
                                                                    Process: com.rescuex_za.rescuex, PID: 32377
                                                                    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                                                                        at com.rescuex_za.rescuex.MenuActivity$1$1.onDataChange(MenuActivity.java:128)
                                                                        at com.google.android.gms.internal.zzegf.zza(Unknown Source)
                                                                        at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
                                                                        at com.google.android.gms.internal.zzeig.run(Unknown Source)
                                                                        at android.os.Handler.handleCallback(Handler.java:739)
                                                                        at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                        at android.os.Looper.loop(Looper.java:135)
                                                                        at android.app.ActivityThread.main(ActivityThread.java:5910)
                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                        at java.lang.reflect.Method.invoke(Method.java:372)
                                                                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)

2 个答案:

答案 0 :(得分:0)

这种情况正在发生,因为constructor(props) { super(props); let comments = [{body: "good", created_at:"2018-02-12T05:27:47.175Z"}, {body: "bad article", created_at:"2017-11-12T05:27:47.175Z"}, {body: "great", created_at:"2017-10-12T05:27:47.175Z"}]; this.state = { comments }; render() { return( { comments.map((comment, index) => <Text>{comment.body}</Text> )} ); }; created_at而您在空对象引用上调用dataSnapshot。要解决此问题,请首先检查null是否存在,因为使用它。

toString()

要仅获取dataSnapshot,请使用以下代码:

if(dataSnapshot != null && dataSnapshot.exists()) {
    //your logic
}

答案 1 :(得分:0)

这是我最终做的但仍然得到同样的错误

这是我的数据库Database(Emergency_Contact)

 emergencyContactDB.addValueEventListener(new ValueEventListener() {
     @Override
     public void onDataChange(DataSnapshot dataSnapshot) {
         if (dataSnapshot != null && dataSnapshot.exists()) {
             user_id = dataSnapshot.child(mCurrentUserId).child(receiver_user_id).getValue().toString();
             if (user_id != null) {
                 addEmergencyMessage();
                 addEmergencyChat();
                 Toast.makeText(getApplicationContext(), "Emergency Alert message was successfully sent",Toast.LENGTH_LONG).show();
             }
         }
         else {
             Toast.makeText(getApplicationContext(), "The Database is Empty",Toast.LENGTH_LONG).show();
         }
     }

     @Override
     public void onCancelled(DatabaseError databaseError) {
         Log.d("TAG",databaseError.getMessage().toString());
     }
});