I have been trying to send a custom message in my database (Emergency_Contact) by a button click (mRescue), when a button is clicked it's going to check the user_id
of the person who pressed the button after that check in Emergency_Contact
for every person who has the senders_user_id
as their child, If they have the sender_user_id
as their child it sends them the message else it return a Toast message. I tried to run my code but it's crashing i don't know why.
this is my activity where this is carried out.
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();
}
}
How can I send this message?
this is my 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)
This is happening because dataSnapshot
is null
and you are calling toString()
on a null object reference. To solve this, check first the dataSnapshot
for existens because using it.
if(dataSnapshot != null && dataSnapshot.exists()) {
//your logic
}
To only get the pJhp...
, please use the following code:
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);