Unable to save the firebase activity state - java

The Main Dashboard File of the App
Dashboard.java
package com.abc.farmersconsult;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
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;
public class RegisterActivity extends AppCompatActivity {
private EditText editText;
private Spinner spinner;
FirebaseAuth mAuth;
DatabaseReference userRef;
FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
spinner = findViewById(R.id.spinner_countries);
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
CountryData.countrynames));
editText = findViewById(R.id.Phone);
findViewById(R.id.Continue).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String code =
CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
Intent intent = new Intent(RegisterActivity.this,
VerifyPhone.class);
intent.putExtra("phonenumbers", phoneNumber);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser=FirebaseAuth.getInstance().getCurrentUser();
UpdateUI(currentUser);
/*
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Intent intent = new Intent(this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} */
}
private void UpdateUI(FirebaseUser currentUser) {
if(currentUser!=null){
Intent intent=new Intent(RegisterActivity.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
This File is The Profile Setup Activity
SetupProfile.java
public class SetupProfile extends AppCompatActivity {
EditText editText;
Button button;
private FirebaseAuth mAuth;
DatabaseReference mUserRef;
String CurrentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup_profile);
mAuth=FirebaseAuth.getInstance();
CurrentUserID=mAuth.getCurrentUser().getUid();
mUserRef=FirebaseDatabase.getInstance().getReference().
child("Users").child(CurrentUserID);
button=(Button)findViewById(R.id.save);
editText=(EditText)findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveAccount();
}
});
}
private void saveAccount() {
String username=editText.getText().toString().trim();
if(username.isEmpty()){
Toast.makeText(this,"Enter valid name", Toast.LENGTH_LONG).show();
}
else{
HashMap userMap= new HashMap();
userMap.put("username",username);
mUserRef.updateChildren(userMap).addOnCompleteListener(new
OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()){
Toast.makeText(SetupProfile.this,"Account
create",Toast.LENGTH_LONG).show();
sendHome();
}
}
});
}
}
private void sendHome() {
Intent intent=new Intent(SetupProfile.this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
This File Contains Verification of the OTP file
VerifyPhone.java
public class VerifyPhone extends AppCompatActivity {
private String verificationId;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
private EditText editText;
DatabaseReference userRef;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
editText = findViewById(R.id.verify_otp);
String phonenumber = getIntent().getStringExtra("phonenumbers");
sendVerificationCode(phonenumber);
findViewById(R.id.Sign).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = editText.getText().toString().trim();
if (code.isEmpty() || code.length() < 6) {
editText.setError("Enter code...");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
signInWithCredential(credential);
}
private void checkExistence() {
}
private void SendUserToSetup() {
Intent intent=new Intent(VerifyPhone.this, SetupProfile.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
private void signInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
final String current_userid=mAuth.getCurrentUser().getUid();
userRef= FirebaseDatabase.getInstance().getReference().child("Users");
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(current_userid)){
SendUserToSetup();
}
else {
Intent intent = new Intent(VerifyPhone.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Toast.makeText(VerifyPhone.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
}
private void sendVerificationCode(String number) {
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new
PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken
forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential credential) {
String code = credential.getSmsCode();
if (code != null) {
editText.setText(code);
verifyCode(code);
}
signInWithCredential(credential);
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhone.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
RegisterPhone.java
package com.abc.farmersconsult;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class RegisterActivity extends AppCompatActivity {
private EditText editText;
private Spinner spinner;
FirebaseAuth mAuth;
DatabaseReference userRef;
FirebaseAuth.AuthStateListener mAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
spinner = findViewById(R.id.spinner_countries);
spinner.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
CountryData.countrynames));
editText = findViewById(R.id.Phone);
findViewById(R.id.Continue).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String code =
CountryData.countryAreaCodes[spinner.getSelectedItemPosition()];
String number = editText.getText().toString().trim();
if (number.isEmpty() || number.length() < 10) {
editText.setError("Valid number is required");
editText.requestFocus();
return;
}
String phoneNumber = "+" + code + number;
Intent intent = new Intent(RegisterActivity.this,
VerifyPhone.class);
intent.putExtra("phonenumbers", phoneNumber);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser=FirebaseAuth.getInstance().getCurrentUser();
UpdateUI(currentUser);
/*
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
Intent intent = new Intent(this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} */
}
private void UpdateUI(FirebaseUser currentUser) {
if(currentUser!=null){
Intent intent=new Intent(RegisterActivity.this, Dashboard.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
There are Four Files Namely Dashboard.java, VerifyPhone.java, RegisterPhone.java and SetupProfile.java, I am able to perform OTP Authentication Successfully and Move to Setup Profile Activity and then the app moves to the Dashboard.java
The Problem is if I exit the app it starts with Dashboard.java,it doesnot resume the profile setup activity.
It directly logs into the Dashboard everytime i perform sign in, I want the app to resume the incomplete account setup upon opening the application please help

After trying to understand your code (which you need to improve on how to write it in StackOverflow), I think the problem is because you just forget to sign-out when the app exit.
Firebase will keep your user signed-in, even after you exit your app. So that's why in your RegisterActivity, the result will always come true, as there is always a FirebaseUser in FirebaseAuth. Solution is: You have to make sure they signed-out when they re-enter the app.
Suggestions
You can signout every time your Activity is destroyed (or everytime user opens the app). Making sure they always start fresh.

Related

add data to listview from another activity

I'm really confused on how to add from another activity I keep getting an error in this part of the code:
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
So the error says "actual and formal argument lists differ in length". if anyone could help me out it would be such a huge help thank you :)
this my code:
main activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button newEmail;
private ListView listView;
private EmailAdapter emailAdapter;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
emailAdapter = new EmailAdapter(this, emailsArrayList);
listView.setAdapter(emailAdapter);
updateList();
newEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SendActivity.class);
startActivity(intent);
}
});
}
private void init(){
newEmail = (Button) findViewById(R.id.newBtn);
listView = (ListView) findViewById(R.id.list);
emailsArrayList = new ArrayList<>();
Emails emails = new Emails ();
emails.setEmails("josemari#yahey.com");
emails.setSubject("Sample Data");
emails.setBody("this is the sample data");
emailsArrayList.add(emails);
}
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if(requestCode == 1 && resultCode == RESULT_OK)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d("MainActivity","onStart invoked");
}
#Override
protected void onResume() {
super.onResume();
Log.d("MainActivity","onResume invoked");
}
#Override
protected void onPause() {
super.onPause();
Log.d("MainActivity","onPause invoked");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onRestart() {
super.onRestart();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
this is the add item activity:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class SendActivity extends AppCompatActivity {
private Button send;
private Button discard;
private EditText email;
private EditText subject;
private EditText body;
private ArrayList<Emails> emailsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
send = (Button) findViewById(R.id.sendBtn);
discard = (Button) findViewById(R.id.discardBtn);
email = (EditText) findViewById(R.id.inputEmail);
subject = (EditText) findViewById(R.id.inputSubject);
body = (EditText) findViewById(R.id.inputBody);
discard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SendActivity.this, MainActivity.class);
startActivity(intent);
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String inputEmail = email.getText().toString();
String inputSubject = subject.getText().toString();
String inputBody = body.getText().toString();
if (inputBody.isEmpty() || inputEmail.isEmpty() || inputEmail.isEmpty()){
Toast.makeText(SendActivity.this, "Please enter the following data", Toast.LENGTH_SHORT).show();
}
else {
emailsArrayList = new ArrayList<>();
Emails newEmails = new Emails ();
newEmails.setEmails(inputEmail);
newEmails.setSubject(inputSubject);
newEmails.setBody(inputBody);
emailsArrayList.add(newEmails);
Intent intent = new Intent();
getIntent().putExtra("inputEmail", inputEmail);
getIntent().putExtra("inputSubject", inputSubject);
getIntent().putExtra("inputBody", inputBody);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
}
I would also change the following as well:
private void updateList()
{
Bundle bundle = getIntent().getExtras();
Intent intent = getIntent();
if(bundle != null)
{
Emails a = new Emails(intent.getStringExtra("inputEmail"), intent.getStringExtra("inputBody"), intent.getStringExtra("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
to
private void updateList()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
if(bundle != null)
{
Emails a = new Emails(String)bundle.get("inputEmail"), (String)bundle.get("inputBody"), (String)bundle.get("inputSubject"));
emailAdapter.add(a);
emailAdapter.notifyDataSetChanged();
}
}
I would try this absolutley first: You may beable to use what you have and just change the Bundle bundle and Intent intent lines around in your updateList(). Again no expert but try that first and then above that second. I hope it works for you.

Failing to stop LoginActivity from popping up while RETURNING to HomeActivity from AnotherActivity

LoginActivity takes user to HomeActivity:
package com.example.spree;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.app.ProgressDialog;
import android.content.Intent;
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.example.spree.Models.Users;
import com.example.spree.Prevalent.Prevalent;
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.rey.material.widget.CheckBox;
import io.paperdb.Paper;
public class LoginActivity extends AppCompatActivity {
private EditText inputPhoneNumber, inputPassword;
private Button loginButton;
private ProgressDialog loadingDialog;
private String parentDBName = "Users";
private TextView adminLink, notAdminLink;
private CheckBox checkBoxRememberMe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputPhoneNumber = findViewById(R.id.login_phone_number_input);
inputPassword = findViewById(R.id.login_password_input);
loginButton = findViewById(R.id.login_btn);
loadingDialog = new ProgressDialog(this);
checkBoxRememberMe = (CheckBox) findViewById(R.id.remember_me_chkb);
Paper.init(this);
adminLink = findViewById(R.id.admin_panel_link);
notAdminLink = findViewById(R.id.not_admin_panel_link);
//onClickListeners
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginUser();
}
});
adminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setText("Login Admin");
adminLink.setVisibility(View.INVISIBLE);
notAdminLink.setVisibility(View.VISIBLE);
parentDBName = "Admins";
}
});
notAdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginButton.setText("Login");
notAdminLink.setVisibility(View.INVISIBLE);
adminLink.setVisibility(View.VISIBLE);
parentDBName = "Users";
}
});
}
private void loginUser() {
String phone = inputPhoneNumber.getText().toString();
String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(phone)) {
Toast.makeText(this, "Please, enter your mobile number.", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please, enter your password.", Toast.LENGTH_SHORT).show();
} else {
loadingDialog.setTitle("Login Account");
loadingDialog.setMessage("Please, wait while we are checking the credentials.");
loadingDialog.setCanceledOnTouchOutside(false);
loadingDialog.show();
allowAccessToUser(phone, password);
}
}
private void allowAccessToUser(final String phone, final String password) {
if(checkBoxRememberMe.isChecked()){
Paper.book().write(Prevalent.userPhoneKey, phone);
Paper.book().write(Prevalent.userPassKey, password);
}
final DatabaseReference myRef;
myRef = FirebaseDatabase.getInstance().getReference();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.child(parentDBName).child(phone).exists()){
Users userData = snapshot.child(parentDBName).child(phone).getValue(Users.class);
// if(userData.getPhone().equals(phone)){
if(userData.getPassword().equals(password)){
if(parentDBName.equals("Admins")){
Toast.makeText(LoginActivity.this, "Admin logged in successfully!", Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else if (parentDBName.equals("Users")) {
Toast.makeText(LoginActivity.this, "User logged in successfully!", Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Prevalent.currentOnlineUser = userData;
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
//ActivityCompat.finishAffinity(LoginActivity.this);
finish();
}
}
else
{
Toast.makeText(LoginActivity.this, "Incorrect password", Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
}
//}
}
else
{
Toast.makeText(LoginActivity.this, "Account with this "+phone+ " doesn't exist", Toast.LENGTH_SHORT).show();
loadingDialog.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
Another activity called ProductDetailActivity is supposed to take user back to HomeActivity on clicking addToCartBtn. However, with the commands for button function erased out, app still takes user to HomeActivity (weird!) while raising a toast from LoginActivity:
A portion of ProductDetailActivity(addToCartButton):
cartList.child("User View").child(Prevalent.currentOnlineUser.getPhone())
.child("Products").child(productID)
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
cartList.child("Admin View").child(Prevalent.currentOnlineUser.getPhone())
.child("Products").child(productID)
.updateChildren(cartMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}
}
});
}
}
});
Why does my application takes user back to home activity while raising a toast that says "user logged in successfully although the commands for button function in ProductDetailActivity have been erased out?
I've tried uninstalling then reinstalling the app to gain logical (expected) behavior. No success. I've tried rebuilding; again, no success. I've tried using
(1)finish();
(2) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); and
(3)ActivityCompat.finishAffinity(LoginActivity.this);
Again, no success.
You can check out the full code of related activities from the link provided:
full codes
You may refer to snapshot for clearer understanding of the situation:
Snapshot of Activity transitions
If anyone's viewed my question on kept on wondering why? I have found a solution (Yay!). In my LoginActivity I have written:
myRef.addValueEventListener(new ValueEventListener() {...
But I should have written instead:
myRef.addListenerForSingleValueEvent(new ValueEventListener() {...
Because addValueEventListener() keep listening to query or database reference it is attached to. But addListenerForSingleValueEvent() executes onDataChange method immediately and after executing that method once,it stops listening to the reference location it is attached to. Thus, problem has been resolved.

How can I retrieve a users username from Firebase Realtime database for a welcome back message?

I have an android studio project whereby the user logins in with an email address and password. The user's username is stored in Firebase's realtime database upon registration.
How would i retrieve the username from the database so that i can display a welcome back (username) message after successful login?
I have attached the home screen java, this is where i would like the message to appear.
I have also attached the login java where the user enters their email and password.
The register class where the user enters their details and the user class.
Thanks in advance, am pretty new to code so pardon my ignorance.
package com.example.securityapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
public class home extends AppCompatActivity {
Button training;
Button signOut;
Button loginPage;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
training = (Button) findViewById(R.id.training_button);
signOut = (Button) findViewById(R.id.sign_out);
mAuth = FirebaseAuth.getInstance();
FirebaseAuth mAuth;
}
public void signOutUser() {
mAuth.signOut();
Toast.makeText(home.this, "Sign out successful!", Toast.LENGTH_LONG).show();
Intent intent_signout = new Intent(home.this, login.class);
startActivity(intent_signout);
finish();
}
public void SignoutOnClick(View view) {
signOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signOutUser();
}
});
}
public void TrainingOnClick(View view) {
training.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_training = new Intent(home.this, training.class);
startActivity(intent_training);
finish();
}
});
}
public void loginOnClick (View view){
loginPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_login = new Intent(home.this, register.class);
startActivity(intent_login);
finish();
}
});
}
}
package com.example.securityapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
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.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class register extends AppCompatActivity {
private FirebaseAuth mAuth;
EditText emailReg, passwordReg, password2, roleReg, officeReg;
Button regButton;
DatabaseReference databaseUsers;
EditText usernameReg;
FirebaseDatabase database = FirebaseDatabase.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
emailReg = (EditText) findViewById(R.id.regEmail);
usernameReg = (EditText) findViewById(R.id.regUsername);
passwordReg = (EditText) findViewById(R.id.regPassword);
regButton = (Button) findViewById(R.id.register_Button);
password2 = (EditText) findViewById(R.id.confirm_password);
roleReg = (EditText) findViewById(R.id.regRole);
officeReg = (EditText) findViewById(R.id.regOffice);
databaseUsers = database.getReference();
mAuth = FirebaseAuth.getInstance();
}
public void registerUser() {
final String email = emailReg.getText().toString();
final String password = passwordReg.getText().toString();
String pass2 = password2.getText().toString();
if(!pass2.equals(password))
{
Toast.makeText(register.this, "Passwords Do Not Match",
Toast.LENGTH_SHORT).show();
return;
}
//Code taken from https://firebase.google.com/docs/auth/android/start on 10/11/2019
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
insertDataDB();
Intent intent_signup = new Intent(register.this, home.class);
startActivity(intent_signup);
finish();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(register.this, "Authentication Successful!",
Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(register.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
public void registerOnClick(View view)
{
regButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
registerUser();
}
});
}
public void insertDataDB()
{
String username = usernameReg.getText().toString();
String job = roleReg.getText().toString();
String email = emailReg.getText().toString();
String office = officeReg.getText().toString();
String id = databaseUsers.push().getKey();
Users user1 = new Users(username, job, email, office);
databaseUsers.child(id).setValue(user1);
}
}
package com.example.securityapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
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;
public class login extends AppCompatActivity
//implements View.OnClickListener
{
Button signUp;
Button login;
EditText etEmail;
EditText etPassword;
ProgressBar bar;
FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
signUp = (Button) findViewById(R.id.signUp_button);
login = (Button) findViewById(R.id.login_button);
etEmail = (EditText)findViewById(R.id.email_input);
etPassword = (EditText)findViewById(R.id.password_input);
bar = (ProgressBar) findViewById(R.id.progressBar);
bar.setVisibility(View.GONE);
mAuth = FirebaseAuth.getInstance();
}
#Override
public void onStart()
{
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
}
//Code taken from https://firebase.google.com/docs/auth/android/password-auth on 06/11/2019
public void loginUser()
{
final String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if(email.isEmpty()&&password.isEmpty())
{
Toast.makeText(login.this, "Email and password cannot be empty.",
Toast.LENGTH_SHORT).show();
bar.setVisibility(View.GONE);
}else if(email.isEmpty())
{
Toast.makeText(login.this, "Email cannot be empty.",
Toast.LENGTH_SHORT).show();
bar.setVisibility(View.GONE);
}else if(password.isEmpty())
{
Toast.makeText(login.this, "Password cannot be empty.",
Toast.LENGTH_SHORT).show();
bar.setVisibility(View.GONE);
}else
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
//Log.d(TAG, "signInWithEmail:success");
// FirebaseUser user = mAuth.getCurrentUser();
bar.setVisibility(View.VISIBLE);
Intent intent_home = new Intent(login.this, home.class);
startActivity(intent_home);
finish();
Toast.makeText(login.this, "Login successful",
Toast.LENGTH_SHORT).show();
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
//Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(login.this, "Incorrect Email or Password.",
Toast.LENGTH_SHORT).show();
bar.setVisibility(View.GONE);
//updateUI(null);
}
// ...
}
});
}
public void loginOnClick (View view)
{
login.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
bar.setVisibility(View.VISIBLE);
loginUser();
}
});
}
public void RegisterOnClick (View view)
{
signUp.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent_reg = new Intent(login.this, register.class);
startActivity(intent_reg);
finish();
}
});
}
}
package com.example.securityapp;
public class Users {
String username;
String job;
String email;
String office;
public Users() {
}
public Users(String username, String job, String email, String office) {
this.username = username;
this.job = job;
this.email = email;
this.office = office;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
}
Try with this...
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();
// User is signed in
} else {
// No user is signed in
}
Follow the Firebase documnets
take a look at this method:
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
// Do something here...
} else {
// If sign in fails, display a message to the user..
}
}
});
When signIn enter in the method onComplete you can use
FirebaseUser user = mAuth.getCurrentUser()
in order to get any information do you want about the user such as email, name and so on.

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.

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.

Categories