App crashes whenever I log out, authentication with firebase - java

i'm creating a sing in up and whenever i log in then log out i crash, I get this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at net.app.MainActivity.onCreate(MainActivity.java:89)
with the line 89 being:
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
and the mainactivity code is:
package net.smallacademy.authenticatorapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int GALLERY_INTENT_CODE = 1023 ;
TextView fullName,email,phone,verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
Button resetPassLocal,changeProfileImage;
FirebaseUser user;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialize variable for navigation
BottomNavigationView bottomNavigationView=findViewById(R.id.bottom_navigation);
//set home to be selected
bottomNavigationView.setSelectedItemId(R.id.profile);
//preform itemselectedlistener
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
startActivity(new Intent(getApplicationContext(),home.class));
overridePendingTransition(0,0);
return true;
case R.id.profile:
return true;
case R.id.exercice:
startActivity(new Intent(getApplicationContext(),hi.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
phone = findViewById(R.id.profilePhone);
fullName = findViewById(R.id.profileName);
email = findViewById(R.id.profileEmail);
resetPassLocal = findViewById(R.id.resetPasswordLocal);
profileImage = findViewById(R.id.profileImage);
changeProfileImage = findViewById(R.id.changeProfile);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 8 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(),EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
//
}
});
}
//this is the logout function
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(),Login.class));
Toast.makeText(this,"Logging Out",Toast.LENGTH_SHORT).show();
finish();
}
}
I don't get why it's happening,it was working fine before

Before using fAuth.getCurrentUser().getUid() check if there is a user currently signed in
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
StorageReference profileRef= storageReference.child("users/"+user.getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>(){
#Override
public void onSuccess(Uri uri){
Picasso.get().load(uri).into(profileImage);
}
});
}
That should solve the problem, but still you will have to handle a user not signed in

Related

How to make app able to show notification when it is closed

I have included a chatting feature in my app using Firebase realtime Database.
I want to be able to show notification when another user sends a message even when the app is turned but I'm not sure how
package com.example.android.crazytenmessenger;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.android.crazytenmessenger.auth.UserProfileActivity;
import com.example.android.crazytenmessenger.dao.MessageDAOHelper;
import com.example.android.crazytenmessenger.utils.DateUtils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.OnProgressListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.List;
public class MessagingActivity extends AppCompatActivity {
private ListView listView;
private FloatingActionButton sendButton;
private EditText messageEditTextBox;
private ProgressBar progressBar;
private ImageView imagePicker;
private static final String TAG=MessagingActivity.class.getSimpleName();
private static final int MAX_WORD_LIMIT = 1000;
private DatabaseReference messageDatabaseReference;
private FirebaseStorage firebaseStorage;
private StorageReference chatPhotoStorageReference;
private ChildEventListener childEventListener;
private List<Message> messages;
private SharedPreferences sharedPreferences;
private String username;
private MessageDAOHelper daoHelper;
private MessageAdapter messageAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_messaging);
listView=(ListView) findViewById(R.id.message_list_view);
messageEditTextBox=(EditText) findViewById(R.id.message_box);
sendButton=(FloatingActionButton) findViewById(R.id.send_button);
imagePicker=(ImageView) findViewById(R.id.image_picker);
progressBar=(ProgressBar) findViewById(R.id.progress_Bar);
daoHelper=new MessageDAOHelper();
messageDatabaseReference=daoHelper.getMessageDatabaseReference();
firebaseStorage=FirebaseStorage.getInstance();
chatPhotoStorageReference=firebaseStorage.getReference().child("chat_photos");
sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
messages=new ArrayList<>();
loadPreviousMessages();
messageAdapter=new MessageAdapter(this,R.layout.item_message,messages);
listView.setAdapter(messageAdapter);
username=FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
ActivityResultLauncher<String> mGetContent=registerForActivityResult(new ActivityResultContracts.GetContent(),
new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
uploadPhoto(result);
}
});
childEventListener=new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) {
Message currentMsg=snapshot.getValue(Message.class);
messageAdapter.add(currentMsg);
listView.smoothScrollToPosition(messageAdapter.getCount());
}
#Override
public void onChildChanged(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) { }
#Override
public void onChildRemoved(#NonNull DataSnapshot snapshot) {
Snackbar.make(findViewById(android.R.id.content),"succesfully removed", BaseTransientBottomBar.LENGTH_SHORT).show();
Log.v(TAG,"Removed : "+snapshot.getValue());
}
#Override
public void onChildMoved(#NonNull DataSnapshot snapshot, #Nullable String previousChildName) { }
#Override
public void onCancelled(#NonNull DatabaseError error) { }
};
messageEditTextBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(s.toString().trim().length()>0)
sendButton.setEnabled(true);
else
sendButton.setEnabled(false);
}
#Override
public void afterTextChanged(Editable s) { }
});
messageEditTextBox.setFilters(new InputFilter[]{new InputFilter.LengthFilter(MAX_WORD_LIMIT)});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username=sharedPreferences.getString(getString(R.string.my_profile_username_key),"USER");
username=FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String timeStamp= DateUtils.getCurrentTimestamp();
Message message=new Message(messageEditTextBox.getText().toString(),username, null, timeStamp);
daoHelper.addMessage(message).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(findViewById(android.R.id.content),"Message Not Sent "+e.getMessage(), BaseTransientBottomBar.LENGTH_SHORT).show();
}
});
messageEditTextBox.setText("");
}
});
imagePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGetContent.launch("image/*");
}
});
messageDatabaseReference.addChildEventListener(childEventListener);
}
/**
* Signing in the the current user automatically using OnStart
* Using Firebase Auth getCurrentUser
*/
#Override
protected void onStart() {
super.onStart();
String user= FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
if(user==null)
user="";
Snackbar.make(findViewById(android.R.id.content),"Welcome "+user,BaseTransientBottomBar.LENGTH_SHORT).show();
}
public void uploadPhoto(Uri uri){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Uploading Image.....");
progressDialog.show();
StorageReference photoRef=chatPhotoStorageReference.child(uri.getLastPathSegment());
photoRef.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> result=taskSnapshot.getMetadata().getReference().getDownloadUrl();
progressDialog.dismiss();
result.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String timeStamp=DateUtils.getCurrentTimestamp();
Message newMessage=new Message(null,username,uri.toString(), timeStamp);
daoHelper.addMessage(newMessage);
}
});
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double percentage=(100.00*snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
Log.v(TAG,"Progress : "+percentage);
progressDialog.setMessage("Progress : "+(int)percentage+"%");
}
});
Toast.makeText(this,"Image uploaded",Toast.LENGTH_SHORT).show();
}
private void deleteAllMessages(){
AlertDialog dialog=new AlertDialog.Builder(this)
.setTitle("Delete all messages")
.setMessage("Are you sure you want to delete all messages")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Deleting... ",Toast.LENGTH_SHORT).show();
messageDatabaseReference.removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
}
});
chatPhotoStorageReference.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(),"All files Deleted ",Toast.LENGTH_SHORT).show();
messages.clear();
messageAdapter.notifyDataSetChanged();
listView.setAdapter(messageAdapter);
loadPreviousMessages();
}
});
}
})
.setNegativeButton(android.R.string.no,null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
private void loadPreviousMessages(){
messageDatabaseReference.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if(!task.isSuccessful())
Log.e(TAG,"Error in retrieving data ",task.getException());
else{
int count= (int) task.getResult().getChildrenCount();
if(count==0){
Snackbar.make(findViewById(android.R.id.content),
"Let's start chatting",
BaseTransientBottomBar.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
return;
}
progressBar.setVisibility(View.GONE);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id=item.getItemId();
if(id==R.id.profile_menu){
Intent intent=new Intent(MessagingActivity.this, UserProfileActivity.class);
startActivity(intent);
}else if(id==R.id.delete_all_option){
deleteAllMessages();
}else if(id==R.id.signout){
signoutCurrentUser();
}
return super.onOptionsItemSelected(item);
}
private void signoutCurrentUser() {
FirebaseAuth.getInstance().signOut();
finish();
}
}
I used child event listeners on firebase database reference to know the message sent but how to use it for notification.
You should use FCM for targeting the notification.
Whenever a message is sent(data inserted in the Firebase DB) you need to pull the data from DB and send a notification to the particular device using registration ID of the device.
The FCM notifaction should be a data type(user defined payload) if you wish your app to receive notification even when the app is in background or closed.
You can use Notification Type (the object holds "notification" as Key), this will work only when the app is in foreground.
Take a look at this
https://firebase.google.com/docs/cloud-messaging/concept-options
You can not show it through your app. It is system feature.
https://firebase.google.com/docs/cloud-messaging/concept-options
your json body should include
"notification":{
"title":"Portugal vs. Denmark",
"body":"great match!"
}

Activity opening itself [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am creating a chat app. users can change their info. after making a new account, they have to create their profile. the profile activity restarts itself again and again. can I fix it or It is an Android problem
I have tried everything at here!
settingsActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button Updatebutton;
private EditText Username, Status;
private CircleImageView profileImage;
private String currentUID;
private DatabaseReference rootref;
private StorageReference ProfileImagesRef;
private String downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Uri resultUri = result.getUri();
final StorageReference ref = ProfileImagesRef.child(currentUID + ".jpg");
ref.putFile(resultUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(SettingsActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
rootref.child("Users").child(currentUID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully...", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SettingsActivity.this, "Some error has occurred, please try again later...", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
}
}
}
private void getUserInfo()
{
rootref.child("Users").child(currentUID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String oldImage;
if(dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("status"))) {
String oldUsername = dataSnapshot.child("name").getValue().toString();
String oldStatus = dataSnapshot.child("status").getValue().toString();
Username.setText(oldUsername);
Status.setText(oldStatus);
}
if (dataSnapshot.hasChild("image"))
{
oldImage = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(oldImage).placeholder(R.drawable.profile_image).into(profileImage);
}
Toast.makeText(SettingsActivity.this, "Please update your profile", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void updateSettings()
{
String setUserName = Username.getText().toString();
String setStatus = Status.getText().toString();
if (TextUtils.isEmpty(setUserName))
{
Toast.makeText(this, "Please enter Username to continue", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus))
{
Toast.makeText(this, "Please enter Status to continue", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
rootref.child("Users").child(currentUID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
askUserToUseApp();
}
else
{
String messegess = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
rootref = FirebaseDatabase.getInstance().getReference();
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile images");
initializeFields();
Updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSettings();
}
});
getUserInfo();
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
}
});
updateUserStatus("online");
}
private void initializeFields()
{
Updatebutton = findViewById(R.id.update_settings);
Username = findViewById(R.id.set_user_name);
Status = findViewById(R.id.set_status);
profileImage = findViewById(R.id.set_profile_image);
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(SettingsActivity.this, MainActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
protected void onStop()
{
super.onStop();
updateUserStatus("offline");
}
#Override
protected void onDestroy()
{
super.onDestroy();
updateUserStatus("offline");
}
private void updateUserStatus(String state)
{
Calendar calForDate = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM, yyyy");
String currentDate = simpleDateFormat.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm:ss a");
String currentTime = simpleTimeFormat.format(calForTime.getTime());
HashMap<String, Object> onlineState = new HashMap<>();
onlineState.put("time", currentTime);
onlineState.put("date", currentDate);
onlineState.put("state", state);
rootref.child("Users").child(currentUID).child("userState")
.updateChildren(onlineState);
}
}
there are no errors. but I can stop it by uninstalling it using ADB
Edit: it works fine after I edit it manually edit in firebase and then open that activity from the main activity.
Edit2:
registerActivity.java
package com.satyamedh.chitchatmessenger;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
public class ResigsterActivity extends AppCompatActivity {
private Button registerButton;
private EditText userEmail, userPassword;
private TextView loginactivityLink;
private FirebaseAuth mAuth;
private DatabaseReference rootref;
private ProgressDialog loading_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resigster);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
rootref = FirebaseDatabase.getInstance().getReference();
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.register_banner_ad);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
initializeFields();
loginactivityLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
askUserToLogin();
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createAccount();
}
});
}
private void createAccount()
{
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please enter Email...", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please enter Password...", Toast.LENGTH_SHORT).show();
}
else
{
loading_bar.setTitle("Creating new account");
loading_bar.setMessage("Please wait...");
loading_bar.setCanceledOnTouchOutside(true);
loading_bar.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
final String currentUserID = mAuth.getCurrentUser().getUid();
rootref.child("Users").child(currentUserID).setValue("");
final String[] deviceToken = new String[1];
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken[0] = instanceIdResult.getToken();
// Do whatever you want with your token now
// i.e. store it on SharedPreferences or DB
// or directly send it to server
rootref.child("Users").child(currentUserID).child("device_token").setValue(deviceToken[0]).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(ResigsterActivity.this, "Account created successfully...", Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
mAuth.signInWithEmailAndPassword(email, password);
askUserToMain();
}
}
});
rootref.child("Users").child(currentUserID).child("image").setValue("https://firebasestorage.googleapis.com/v0/b/chit-chat-web-chat.appspot.com/o/profile_image.png?alt=media&token=12bc53c2-c27d-420f-9d5f-f84c22a6449c");
rootref.child("Users").child(currentUserID).child("name").setValue("Enter your name here");
rootref.child("Users").child(currentUserID).child("status").setValue("Enter your status here");
}
});
}
else
{
String messegess = task.getException().toString();
Toast.makeText(ResigsterActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
}
}
});
}
}
private void initializeFields()
{
registerButton = (Button) findViewById(R.id.register_button);
userEmail = (EditText) findViewById(R.id.register_email);
userPassword = (EditText) findViewById(R.id.register_password);
loginactivityLink = (TextView) findViewById(R.id.register_sign_in);
loading_bar = new ProgressDialog(this);
}
private void askUserToLogin() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void askUserToMain() {
Intent mainIntent = new Intent(ResigsterActivity.this, ProfileActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
Might be not related answer but whenever you are using any firebase or firestore
event try to pass "this("activity context")" as the first parameter it will manage the
activity life cycle and will remove you listener when your app will be in background.

Firebase not uploading files to Storage Bucket

I am creating a chat app in which Users can create groups. when a users creates a group, he/she can choose a group profile image. but if i choose the image, it wont upload. what to do?
I have inspected the code, there is no error anywhere
CreateGroupActivity.java:
package com.satyamedh.chitchatmessenger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CreateGroupActivity extends AppCompatActivity
{
private CircleImageView circleImageView;
private EditText editText;
private Button buttonconf, buttoncanc;
private Uri resultUri;
private final static int chosenProfileImage = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
initializeFields();
buttoncanc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
startActivity(profileIntent);
}
});
buttonconf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText.getText())){
Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
else
{
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
String key = rootref.push().getKey();
settingsIntent.putExtra("groupKey", key);
settingsIntent.putExtra("groupImage", resultUri);
settingsIntent.putExtra("groupName", editText.getText().toString());
startActivity(settingsIntent);
}
}
});
circleImageView.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, chosenProfileImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
{
Uri imageUri = data.getData();
CropImage
.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK) {
resultUri = result.getUri();
circleImageView.setImageURI(resultUri);
}
}
}
private void initializeFields()
{
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.my_adView_createGroup);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
circleImageView = findViewById(R.id.create_group_image);
editText = findViewById(R.id.create_group_name);
buttonconf = findViewById(R.id.confirm_button);
buttoncanc = findViewById(R.id.cancel_button);
}
}
chooseUserActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {#link Fragment} subclass.
*/
public class chooseUserActivity extends AppCompatActivity {
private RecyclerView myRecyclerList;
private DatabaseReference ContactsRef, UsersRef;
private String currentUID;
private DatabaseReference groupsRef;
private Button confirmButton;
private String downloadUrl ;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_choose_user);
super.onCreate(savedInstanceState);
initializeFields();
}
private void initializeFields()
{
myRecyclerList = findViewById(R.id.users_choser_group);
myRecyclerList.setLayoutManager(new LinearLayoutManager(chooseUserActivity.this));
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
confirmButton = findViewById(R.id.confirm_group);
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.choose_user_adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
Toolbar toolbar = findViewById(R.id.users_chosers_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Choose users to be in " + getIntent().getExtras().get("groupName").toString());
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContactsRef, Contacts.class)
.build()
;
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>
adapter = new
FirebaseRecyclerAdapter <Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull Contacts model)
{
final String string = getRef(position).getKey();
final String[] image = {"default_image"};
UsersRef
.child(string)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
image[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(image[0]).placeholder(R.drawable.profile_image).into(holder.profileImageView);
}
final String name = dataSnapshot.child("name").getValue().toString();
holder.Username.setText(name);
holder.Userstatus.setText("Last seen: \n");
if(dataSnapshot.child("userState").hasChild("state"))
{
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if(Objects.equals(state, "online"))
{
holder.Userstatus.setText(getString(R.string.Online));
}
else
{
holder.Userstatus.setText(getString(R.string.last_seen) + time + " " + date);
}
}
else
{
holder.Userstatus.setText("Offline");
}
final HashMap<String, Object> hashMap = new HashMap<>();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!hashMap.containsKey(getRef(position).getKey())) {
holder.itemView.setPadding(15, 15, 15, 15);
holder.IsUserInGroup.setVisibility(View.VISIBLE);
if (hashMap.isEmpty()) {
hashMap.put(currentUID, "admin");
}
hashMap.put(getRef(position).getKey(), "non-admin");
}
else {
holder.itemView.setPadding(0, 0, 0, 0);
if (hashMap.size() == 1)
{
hashMap.remove(currentUID, "admin");
}
holder.IsUserInGroup.setVisibility(View.INVISIBLE);
hashMap.remove(getRef(position).getKey(), "non-admin");
}
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
}
});
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
final StorageReference ProfileImagesRef;
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Groups profile images");
final StorageReference ref = ProfileImagesRef.child(getIntent().getExtras().get("groupKey").toString() + ".jpg");
ref.putFile((Uri) getIntent().getExtras().get("groupImage"))
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(chooseUserActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
}
});
}
});
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
groupsRef.child("Users").updateChildren(hashMap);
groupsRef.child("Messages").setValue("");
groupsRef.child("Group info").child("group name").setValue(getIntent().getExtras().get("groupName").toString());
groupsRef.child("Group info").child("group image").setValue(downloadUrl);
Toast.makeText(chooseUserActivity.this, "Group created successfully", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(chooseUserActivity.this, MainActivity.class);
settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(settingsIntent);
finish();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
myRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImageView;
TextView Username, Userstatus;
CheckBox IsUserInGroup;
ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImageView = itemView.findViewById(R.id.users_profile_image);
Username = itemView.findViewById(R.id.users_name);
Userstatus = itemView.findViewById(R.id.users_status);
IsUserInGroup = itemView.findViewById(R.id.IsUserInGroup);
}
}
}
Can anyone help me please?
I fixed it by moving the code in the on success listener itself

App crashes when trying to run in background/foreground but works for other phones

While using android studio and firebase, my app (in the background or foreground) crashes on an API 26 device when notification is clicked. Whereas when I use an API 23 device, the app crashes when the app is closed and notification is clicked but can still process the notification when app is in the background/foreground. I don't understand the problem and any help is appreciated.
NOTIFICATION SERVICE
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.RemoteMessage;
public class FirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String notification_title = remoteMessage.getNotification().getTitle();
String notification_message = remoteMessage.getNotification().getBody();
String click_action = remoteMessage.getNotification().getClickAction();
String from_user_id = remoteMessage.getData().get("from_user_id");
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(FirebaseMessagingService.this, "default")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(notification_title)
.setContentText(notification_message);
Intent resultIntent = new Intent(click_action);
resultIntent.putExtra("user_id", from_user_id);
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
FirebaseMessagingService.this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = (int) System.currentTimeMillis();
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
}
USERS ACTIVITY
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.squareup.picasso.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
public class UsersActivity extends AppCompatActivity {
private Toolbar mToolbar;
private RecyclerView mUsersList;
private DatabaseReference mUsersDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_users);
mToolbar=(Toolbar)findViewById(R.id.users_appBar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("All Users");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mUsersDatabase= FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDatabase.keepSynced(true);
mUsersList=(RecyclerView)findViewById(R.id.users_list);
mUsersList.setHasFixedSize(true);
mUsersList.setLayoutManager(new LinearLayoutManager(this));
}
#Override
protected void onStart() {
super.onStart();
startListening();
}
public void startListening(){
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("Users")
.limitToLast(50);
FirebaseRecyclerOptions<Users> options =
new FirebaseRecyclerOptions.Builder<Users>()
.setQuery(query, Users.class)
.build();
FirebaseRecyclerAdapter<Users, UserViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UserViewHolder>(options) {
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.users_single_layout, parent, false);
return new UserViewHolder(view);
}
#Override
protected void onBindViewHolder(UserViewHolder holder, int position, Users model) {
// Bind the Chat object to the ChatHolder
holder.setName(model.name);
holder.setStatus(model.status);
holder.setUserImage(model.getThumb_image());
final String user_id= getRef(position).getKey();
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(UsersActivity.this, ProfileActivity.class);
if (user_id != null) {
profileIntent.putExtra("user_id", user_id);
startActivity(profileIntent);
}
}
});
}
};
mUsersList.setAdapter(adapter);
adapter.startListening();
}
public static class UserViewHolder extends RecyclerView.ViewHolder {
View mView;
public UserViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setName(String name){
TextView userNameView = (TextView) mView.findViewById(R.id.user_single_name);
userNameView.setText(name);
}
public void setStatus(String status){
TextView userStatusView= (TextView) mView.findViewById(R.id.user_single_status);
userStatusView.setText(status);
}
public void setUserImage(String thumb_image){
CircleImageView userImageView = (CircleImageView) mView.findViewById(R.id.user_single_image);
Picasso.get().load(thumb_image).placeholder(R.drawable.accountpicture).into(userImageView);
}
}
}
PROFILE ACTIVITY
import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
public class ProfileActivity extends AppCompatActivity {
private ImageView mProfileImage;
private TextView mProfileName, mProfileStatus, mProfileFriendsCount;
private Button mProfileSendReqBtn;
private DatabaseReference mUserDatabase;
private Button declineRequest;
private FirebaseUser mCurrent_user;
private ProgressDialog mProgressDialog;
private DatabaseReference mFriendRequestDatabase;
private DatabaseReference mFriendDatabase;
private String mCurrent_state;
private DatabaseReference mNotificationDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final String user_id = getIntent().getStringExtra("user_id");
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mFriendRequestDatabase = FirebaseDatabase.getInstance().getReference().child("Friend_req");
mCurrent_user= FirebaseAuth.getInstance().getCurrentUser();
mFriendDatabase= FirebaseDatabase.getInstance().getReference().child("Friends");
mNotificationDatabase= FirebaseDatabase.getInstance().getReference().child("notifications");
mProfileImage = (ImageView) findViewById(R.id.profile_image);
mProfileName = (TextView) findViewById(R.id.profile_profileName);
mProfileStatus = (TextView) findViewById(R.id.profile_status);
mProfileFriendsCount = (TextView) findViewById(R.id.profile_totalFriends);
mProfileSendReqBtn = (Button) findViewById(R.id.profile_send_req_btn);
declineRequest= (Button)findViewById(R.id.profile_decline_btn);
mCurrent_state = "not_friends";
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setTitle("Loading User Data");
mProgressDialog.setMessage("Please wait...");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
declineRequest.setVisibility(View.INVISIBLE);
if(mCurrent_user.getUid().equals(user_id)){
mProfileSendReqBtn.setVisibility(View.INVISIBLE);
}
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String diplay_name = dataSnapshot.child("name").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
mProfileName.setText(diplay_name);
mProfileStatus.setText(status);
Picasso.get().load(image).networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.accountpicture).into(mProfileImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(image).placeholder(R.drawable.accountpicture).into(mProfileImage);
}
});
mFriendRequestDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
String req_type= dataSnapshot.child(user_id).child("request_type").getValue().toString();
if(req_type.equals("received")){
mCurrent_state= "req_received";
mProfileSendReqBtn.setText("Accept Friend Request");
declineRequest.setVisibility(View.VISIBLE);
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
else if(req_type.equals("sent")){
mCurrent_state="req_sent";
mProfileSendReqBtn.setText("Cancel Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
else if(req_type.equals("req_sent")){
mCurrent_state= "not_friends";
mProfileSendReqBtn.setText("Send Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
mProgressDialog.dismiss();
}
else{
mFriendDatabase.child(mCurrent_user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.hasChild(user_id)){
mCurrent_state= "friends";
mProfileSendReqBtn.setText("Unfriend User");
mProfileSendReqBtn.setEnabled(true);
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
mProgressDialog.dismiss();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
mProgressDialog.dismiss();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mProfileSendReqBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mProfileSendReqBtn.setEnabled(false);
if (user_id.equals(mCurrent_user.getUid())) {
Toast.makeText(ProfileActivity.this, "Cannot send friend request to yourself!", Toast.LENGTH_LONG).show();
declineRequest.setVisibility(View.INVISIBLE);
} else {
if (mCurrent_state.equals("not_friends")) {
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).child("request_type").setValue("sent").addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).child("request_type").setValue("received").addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
HashMap<String, String> notificationData= new HashMap<>();
notificationData.put("from", mCurrent_user.getUid());
notificationData.put("type", "request");
mNotificationDatabase.child(user_id).push().setValue(notificationData).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "req_sent";
mProfileSendReqBtn.setText("Cancel Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
} else {
Toast.makeText(ProfileActivity.this, "Error", Toast.LENGTH_LONG).show();
}
mProfileSendReqBtn.setEnabled(true);
}
});
}
if (mCurrent_state.equals("req_sent")) {
mProfileSendReqBtn.setEnabled(true);
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "req_sent";
mProfileSendReqBtn.setText("Send Friend Request");
mCurrent_state = "not_friends";
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
if (mCurrent_state.equals("req_received")) {
declineRequest.setVisibility(View.INVISIBLE);
mProfileSendReqBtn.setEnabled(true);
final String currentDate = DateFormat.getDateTimeInstance().format(new Date());
mFriendDatabase.child(mCurrent_user.getUid()).child(user_id).setValue(currentDate).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendDatabase.child(user_id).child(mCurrent_user.getUid()).setValue(currentDate).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state = "friends";
mProfileSendReqBtn.setText("Unfriend User");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
});
}
});
}
}
}
});
declineRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
declineRequest.setVisibility(View.INVISIBLE);
mFriendRequestDatabase.child(mCurrent_user.getUid()).child(user_id).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mFriendRequestDatabase.child(user_id).child(mCurrent_user.getUid()).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mCurrent_state= "not_friends";
mProfileSendReqBtn.setText("Send Friend Request");
mUserDatabase.keepSynced(true);
mFriendDatabase.keepSynced(true);
mFriendRequestDatabase.keepSynced(true);
}
});
}
});
}
});
}
}
INDEX.JS FILE
'use strict'
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/*
* 'OnWrite' works as 'addValueEventListener' for android. It will fire the function
* everytime there is some item added, removed or changed from the provided 'database.ref'
* 'sendNotification' is the name of the function, which can be changed according to
* your requirement
*/
exports.sendNotification = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
/*
* You can store values as variables from the 'database.ref'
* Just like here, I've done for 'user_id' and 'notification'
*/
const user_id = context.params.user_id;
const notification_id = context.params.notification_id;
console.log('We have a notification from : ', user_id);
/*
* Stops proceeding to the rest of the function if the entry is deleted from database.
* If you want to work with what should happen when an entry is deleted, you can replace the
* line from "return console.log.... "
*/
if(!change.after.val()){
return console.log('A Notification has been deleted from the database : ', notification_id);
}
/*
* 'fromUser' query retreives the ID of the user who sent the notification
*/
const fromUser = admin.database().ref(`/notifications/${user_id}/${notification_id}`).once('value');
return fromUser.then(fromUserResult => {
const from_user_id = fromUserResult.val().from;
console.log('You have new notification from : ', from_user_id);
/*
* The we run two queries at a time using Firebase 'Promise'.
* One to get the name of the user who sent the notification
* another one to get the devicetoken to the device we want to send notification to
*/
const userQuery = admin.database().ref(`Users/${from_user_id}/name`).once('value');
const deviceToken = admin.database().ref(`/Users/${user_id}/device_token`).once('value');
return Promise.all([userQuery, deviceToken]).then(result => {
const userName = result[0].val();
const token_id = result[1].val();
/*
* We are creating a 'payload' to create a notification to be sent.
*/
const payload = {
notification: {
title : "New Friend Request",
body: `${userName} has sent you a request`,
icon: "default",
click_action : "com.example.****.chattingapp_TARGET_NOTIFICATION"
},
data : {
from_user_id : from_user_id
}
};
/*
* Then using admin.messaging() we are sending the payload notification to the token_id of
* the device we retreived.
*/
return admin.messaging().sendToDevice(token_id, payload).then(response => {
return console.log('This was the notification Feature');
});
});
});
});
ERROR I GET
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.****.chattingapp, PID: *****
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.****.chattingapp/com.example.****.chattingapp.ProfileActivity}: java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.example.****.chattingapp.ProfileActivity.onCreate(ProfileActivity.java:53)
DATABASE VALUES
You removed most of the important rows of the Error.
However you have to look at it very well and even decode it. It was saying that: there is a problem on "ProfileActivity.onCreate()" method when it calls a "Firebase.....child()" method. There are few rows where you call a "child()" method using a Variable (and not a fixed String), so one of them (please check the Error Log and find the line of that "child()" warning) is the real problem.
So I figured out I needed
final String user_id;
String data = getIntent().getStringExtra("user_id");
if (data == null) {
user_id = getIntent().getStringExtra("from_user_id");
} else {
user_id = getIntent().getStringExtra("user_id");
}
I wasn't check what string I was getting from my intents, hence the null exceptions.

Getting "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" in Firebase

Image of DB in firebase console
I don't really know what's wrong here, I am able to add data on the other activity. I am getting error "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" and don't know how to fix. There are 3 other classes created only one other is adding data to firebase realtime database storage.
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Profile extends AppCompatActivity {
EditText fName, lName, PhNo, BDay, Zip;
Button svBtn;
DatabaseReference mDataReference;
String keyUser;
String fNameStr, lNameStr, PhNoStr, BDayStr, ZipStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
keyUser = getIntent().getStringExtra("USER_KEY");
mDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);//error in this line
fName = (EditText) findViewById(R.id.fName);
lName = (EditText) findViewById(R.id.lName);
PhNo = (EditText) findViewById(R.id.phno);
BDay = (EditText) findViewById(R.id.bday);
Zip = (EditText) findViewById(R.id.zip);
svBtn = (Button) findViewById(R.id.svBtn);
svBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fNameStr = fName.getText().toString();
lNameStr = lName.getText().toString();
PhNoStr = PhNo.getText().toString();
BDayStr = BDay.getText().toString();
ZipStr = Zip.getText().toString();
if(!TextUtils.isEmpty(fNameStr) && !TextUtils.isEmpty(lNameStr) && !TextUtils.isEmpty(PhNoStr)) {
DatabaseReference mDataRef = mDataReference.child("Users").push();
mDataRef.child("firstName").setValue(""+fNameStr);
mDataRef.child("lastName").setValue(""+lNameStr);
mDataRef.child("phoneNumber").setValue(""+PhNoStr);
mDataRef.child("isVerified").setValue("verified");
if(!TextUtils.isEmpty(BDayStr)){
mDataRef.child("birthday").setValue(""+BDayStr);
}else{
mDataRef.child("birthday").setValue("null");
}
if(!TextUtils.isEmpty(ZipStr)){
mDataRef.child("zipcode").setValue("ZipStr");
}else{
mDataRef.child("zipcode").setValue("null");
}
Toast.makeText(Profile.this, "User profile added", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, welcome.class));
}else{
Toast.makeText(Profile.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class katiRoll extends AppCompatActivity {
EditText userEdit;
EditText passEdit;
String sUser, sPass;
Button sign;
Button reg;
Boolean signInVLogIn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kati_roll);
float Re = 255;
float Gr = 148;
float Bl = 0;
userEdit = (EditText)findViewById(R.id.user);
passEdit = (EditText)findViewById(R.id.pass);
sign = (Button) findViewById(R.id.sign);
reg = (Button) findViewById(R.id.reg);
userEdit.setTextColor(Color.rgb(Re,Gr,Bl));
passEdit.setTextColor(Color.rgb(Re,Gr,Bl));
sign.setTextColor(Color.rgb(Re,Gr,Bl));
reg.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass)){
signInVLogIn = true;
}else{
signInVLogIn = false;
}
if(user != null && signInVLogIn) {
}else{
//Toast.makeText(katiRoll.this, "Log In Failed", Toast.LENGTH_LONG).show();
}
}
};
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sUser = userEdit.getText().toString().trim();
sPass = passEdit.getText().toString().trim();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass))
{
mAuth.signInWithEmailAndPassword(sUser, sPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, sUser);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(katiRoll.this, "User Login Doesn't Exist" , Toast.LENGTH_LONG).show();
}
}
});
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(katiRoll.this, signUp.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(katiRoll.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(katiRoll.this, welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.akshay.katiroll.R;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class signUp extends AppCompatActivity {
EditText nUser, nPass;
Button registerBtn, backToMain;
ImageButton passVis;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nUser = (EditText) findViewById(R.id.nUser);
nPass = (EditText) findViewById(R.id.nPass);
registerBtn = (Button) findViewById(R.id.registerBtn);
backToMain = (Button) findViewById(R.id.backToMain);
passVis = (ImageButton)findViewById(R.id.passVis);
passVis.setImageResource(R.drawable.open);
passVis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = passVis.getDrawable();
if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.open,null).getConstantState())){
passVis.setImageResource(R.drawable.closed);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}else{
passVis.setImageResource(R.drawable.open);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
}
}
});
float Re = 255;
float Gr = 148;
float Bl = 0;
nUser.setTextColor(Color.rgb(Re, Gr, Bl));
nPass.setTextColor(Color.rgb(Re, Gr, Bl));
registerBtn.setTextColor(Color.rgb(Re, Gr, Bl));
backToMain.setTextColor(Color.rgb(Re, Gr, Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("User");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkForValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Log.d("TAG", "onAuthStateChanged:signed_out");
}
}
};
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String nUserString, nPassString;
nUserString = (nUser.getText().toString().trim());
nPassString = (nPass.getText().toString().trim());
if(nPassString.length()>=6){
if (!TextUtils.isEmpty(nUserString) && !TextUtils.isEmpty(nPassString)) {
mAuth.createUserWithEmailAndPassword(nUserString, nPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("EmailUser").setValue(nUserString);
mChildDatabase.child("PasswordUser").setValue(nPassString);
Toast.makeText(signUp.this, "User Account Created, Check Email For Confirmation", Toast.LENGTH_LONG).show();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
user.sendEmailVerification();
}
startActivity(new Intent(signUp.this, Profile.class));
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(signUp.this, katiRoll.class));
}
});
}
private void checkForValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(signUp.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(signUp.this, welcome.class));
}
}
}
}
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.SecondScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.akshay.katiroll.FirstScreen.katiRoll;
import com.example.akshay.katiroll.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class welcome extends AppCompatActivity {
Button logOutBtn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
float Re = 255;
float Gr = 148;
float Bl = 0;
logOutBtn = (Button)findViewById(R.id.logOutBtn);
logOutBtn.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null) {
}else{
}
}
};
logOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
finish();
startActivity(new Intent(welcome.this, katiRoll.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(mAuthListener);
}
}
The problem that is telling to you is that you are doing wrong the reference, you are trying to get something inside Firebase Database that is not there
This line is telling you that the child("Users").child(KeyUser); does not exist in your current DB structure
To fix this you should see your databse structure and then redo your reference.
if you post a photo of your Firebase DB i will be glad to refactor your code to your needs.
also here you are getting wrong your USER_KEY
keyUser = getIntent().getStringExtra("USER_KEY");
To fix this a short way would be doing this
keyUser = getIntent().getExtras().getString("USER_KEY");
you are geting an intent from where? if you are trying to get a putExtra from another Activity, you are doing it wrong, post where you are seting the extra ("USER_KEY");
Intent.getStringExtra() and Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString()
one quick example to check for extras first would be this
String keyUser;
Bundle extras = getIntent().getExtras();
if(extras == null) {
Log.e("keyUser is null","");
} else {
keyUser= extras.getString("USER_KEY");
}
happy coding

Categories