当前位置: 首页 > 知识库问答 >
问题:

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

屈健柏
2023-03-14

我一直试图通过按钮单击(mRescue)在我的数据库(Emergency_Contact)中发送自定义消息,当单击按钮时,它将检查在签入Emergency_Contact之后按下按钮的人的user_id对于每个拥有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)

共有1个答案

韦繁
2023-03-14

之所以会发生这种情况,是因为dataSnapshot为null,并且您正在对null对象引用调用toString()。要解决此问题,请首先检查dataSnapshot是否存在,因为它正在使用。

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

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

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Emergency_Contact").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();
            Log.d("TAG", key);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
 类似资料:
  • 如何在Kafka中发送同步消息 实现这一点的一种方法是设置properties参数 。 但是我想知道是否有一种甚至直接或替代的方式在Kafka中发送同步消息。(比如producer.sync发送(...)等等)。

  • 我使用quartz调度程序在不同的时间段向不同的报告发送错误消息。我创建了一个每小时运行一次的调度器,它将执行第二个调度器(此处显示的代码)。必须发送消息的时间是从数据库中获取的,并在exp变量中传递。我只能获取数据库中第一行的值,还可以获取一个org。石英ObjectAlreadyExistsException:无法存储作业:“q3Job”。cronJob3',因为已经存在一个具有此标识的。”错

  • 主要内容:1 invokeOneway单向发送,1.1 invokeOnewayImpl单向调用,2 sendMessageSync同步发送,2.1 invokeSync同步调用,3 sendMessageAsync异步发送消息,3.1 invokeAsync异步调用,3.2 onExceptionImpl异常处理,4 NettyClientHandler处理服务端消息,4.1 processResponseCommand处理响应,基于RocketMQ release-4.9.3,深入的介绍了P

  • 我有两个独立实例(p1、p2)的生产者应用程序和两个独立实例(c1、c2)的消费者应用程序。 生产者p1连接到exchange,主题为t1,队列名称为name1。 使用者c1连接到exchange,主题为t1,队列名称为name1。 生产者p2连接到exchange,主题为t2,队列名称为name1。 使用者c2连接到exchange,主题为t2,队列名称为name1。 我在RabbitMQ GU

  • 我已经阅读了文档,但我发现它很难理解,我将感谢任何帮助!

  • 问题内容: 我有一个JTextArea在我的主应用程序窗口中始终可见(如果需要,则为Log),并且我想使用它来显示系统中正在进行的活动(如您将对System.out.println( )(如果有条件或其他条件) 我指的是用户所做的高级操作(例如“成功加载文件”或“写入磁盘”,“完成”等) 这样的消息可以在我的系统中的任何地方生成,主要是在另一个包中,这些包的类处理数据和计算,并且它们不知道GUI。