After Successful log in my SignIn activity intent to BloodBank activity and the activity check if there any Currentuser or not.
In my case when it comes to BloodBank activity after log in, the method returning current user is null always
Is there any idea how I can resolve this issue?
Here is my SignIn Activity.java
public class SignIn extends AppCompatActivity {
Button signIn,forgetPass;
TextView backToSignUp,number,password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
signIn=findViewById(R.id.signInButtonId);
forgetPass=findViewById(R.id.forgetPassButtonId);
backToSignUp=findViewById(R.id.signUpBack);
number=findViewById(R.id.signInNumberId);
password=findViewById(R.id.signInPasswordId);
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String _phone = number.getText().toString().trim();
final String _password = password.getText().toString().trim();
if (_phone.isEmpty()) {
number.setError("Enter Your Phone Number");
number.requestFocus();
return;
}
if (_password.isEmpty()) {
password.setError("Enter a password");
password.requestFocus();
return;
}
DatabaseReference reference= FirebaseDatabase.getInstance().getReference("BloodBank_users");
Query checkUser=reference.orderByChild("phone").equalTo(_phone);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
number.setError(null);
number.setEnabled(true);
String passwordFromDB = snapshot.child(_phone).child("password").getValue(String.class);
if (passwordFromDB.equals(_password)) {
password.setError(null);
password.setEnabled(true);
Intent intent = new Intent(getApplicationContext(),BloodBankMain.class);
startActivity(intent);
finish();
} else {
password.setError("Wrong Password Or User Name");
password.requestFocus();
}
}
else {
number.setError("This Number Is Not Registered");
number.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
}
Here is my BloodBank.Java
public class BloodBank extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blood_bank);
firebaseAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth){
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
Intent intent = new Intent(BloodBank.this, BloodBankMain.class);
startActivity(intent);
finish();
}
else{
Intent intent = new Intent(BloodBank.this,SignIn.class);
startActivity(intent);
finish();
}
}
};
}
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onResume() {
super.onResume();
firebaseAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
firebaseAuth.removeAuthStateListener(mAuthListener);
}
}
Related
I have a Fragment with a signOut button in my android studio app that is supposed to log the user out of his account and then redirect him back to the login page. I've tried several things so far and looked at every thread I could find but nothing is working. There is no error, just no reaction at all.
First thing I've tried is this:
public class PreferenceFragment extends Fragment {
private PreferenceViewModel preferenceViewModel;
private FragmentPreferenceBinding binding;
private Button btnSignOut;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener authListener;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
preferenceViewModel =
new ViewModelProvider(this).get(PreferenceViewModel.class);
auth = FirebaseAuth.getInstance();
View view = inflater.inflate(R.layout.fragment_preference, container, false);
btnSignOut = (Button) view.findViewById(R.id.sign_out);
binding = FragmentPreferenceBinding.inflate(inflater, container, false);
View root = binding.getRoot();
final TextView textView = binding.textPreference;
preferenceViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = auth.getCurrentUser();
if (user == null) {
// user auth state is changed - user is null
// launch login activity
startActivity(new Intent(getActivity(), LoginActivity.class));
getActivity().finish();
}
}
};
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
}
});
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
This is my LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
First I thought it might be the signOut() that isn't working as intended or logging me back in automatically. But if I put the signOut() into the onStop() method of the MainActivity it is working, obviously only when I close the app:
#Override
public void onStop() {
super.onStop();
FirebaseAuth.getInstance().signOut();
}
then I thought the program might not be calling the same FirebasAuth instance so I've tried calling the FirebaseAuth instance from the MainActivity to the same effect:
(MainActivity)getActivity()).auth.signOut();
I've tried several other things like putting the authListener in the MainActivity or removing the code calling the FirebasAuth instance at the start of the LoginActivity, always to the same effect. Maybe it has to do with my startActivity but I'm not sure how to do it differently. Thanks in advance for any help.
I am having difficulty setting an ImageView with a string download url that is in a user object that came from the firebase storage DB. The method setImage() is saying the Imageview is a null object and this is true as I have tried to debug it and it comes up as null. How can I resolve this. I think it has something to do with the anonymous inner class.
public class DashBoard extends AppCompatActivity {
private FirebaseAuth mAuth;
private ArrayList<String> motivatingMessages;
private Button gymLocations, profile,health;
public ImageView profileImageView;
private TextView welcome;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showProfilePicture();
profileImageView = findViewById(R.id.personalProfile);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
setContentView(R.layout.activity_dash_board);
//getSupportActionBar().setTitle("Welcome To Bodify");
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
if (user != null) {
welcome.setText("User Logged in: ");
welcome.append(user.getUserName());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
gymLocations.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), GymsNearMe.class));
}
});
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), PersonalProfile.class));
}
});
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(DashBoard.this,Health.class));
}
});
}
public void showProfilePicture() {
mAuth = FirebaseAuth.getInstance();
final String userID = mAuth.getUid();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("User").child(userID);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
String image = user.getmImageUrl();
setImage(image);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(DashBoard.this, "Error Occurred: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
public void setImage(String image) {
Picasso.get().load(image).into(profileImageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logOut) {
mAuth.signOut();
startActivity(new Intent(getApplicationContext(), LogIn.class));
}
return true;
}
}
enter code here
It looks like you are trying to find the view before inflating the layout:
profileImageView = findViewById(R.id.personalProfile);
move that line after the inflation so after the line:
setContentView(R.layout.activity_dash_board);
In other words, the order of the lines should be:
setContentView(R.layout.activity_dash_board);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
profileImageView = findViewById(R.id.personalProfile);
showProfilePicture();
and you do not need to set the mAuth again in the showProfilePicture
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dash_board);
profileImageView = findViewById(R.id.personalProfile);
profile = findViewById(R.id.buttonProfile);
gymLocations = findViewById(R.id.gymFinderButton);
health = findViewById(R.id.healthButton);
welcome = findViewById(R.id.welcomeUser);
showProfilePicture();
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = mAuth.getCurrentUser();
try with this order
When I click the Login or Register button the app completely crashes. I cant seem to figure out what the issue is. I'm new to Android so any help or recommendations would be greatly appreciated.
Login Java Class
public class LoginActivity extends AppCompatActivity {
private Button mLogin;
private EditText mEmail, mPassword;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null){
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mLogin = findViewById(R.id.Login);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(LoginActivity.this, "sign in error", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
Registration Java class
public class RegistrationActivity extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mName;
private RadioGroup mRadioGroup;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null){
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
finish();
return;
}
}
};
mRegister = findViewById(R.id.Register);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mName = findViewById(R.id.name);
mRadioGroup = findViewById(R.id.radioGroup);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selectId = mRadioGroup.getCheckedRadioButtonId();
final RadioButton radioButton = findViewById(selectId);
if(radioButton.getText() == null){
return;
}
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String name = mName.getText().toString();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()){
Toast.makeText(RegistrationActivity.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
Map userInfo = new HashMap<>();
userInfo.put("name", name);
userInfo.put("sex", radioButton.getText().toString());
userInfo.put("profileImageUrl", "default");
currentUserDb.updateChildren(userInfo);
}
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(firebaseAuthStateListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(firebaseAuthStateListener);
}
}
Here are the errors I receive from the Logcat:
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##17.1.0:186)
at com.google.firebase.auth.FirebaseAuth.getInstance(com.google.firebase:firebase-auth##18.1.0:1)
at mothership.example.room8.LoginActivity.onCreate(LoginActivity.java:33)
at android.app.Activity.performCreate(Activity.java:7136)
at android.app.Activity.performCreate(Activity.java:7127)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
You are not initializing the FirebaseApp. In onCreate(), write this first:
FirebaseApp.initializeApp(this);
Do this in both of your activities onCreate()
Also add following dependencies:
In your project level gradle file:
dependencies {
....
classpath 'com.android.tools.build:gradle:3.4.2'
classpath 'com.google.gms:google-services:4.3.0'
}
In your app level gradle file:
Add this on top of the file
apply plugin: 'com.google.gms.google-services'
Structure of database
At first , while testing when the user is logged in or fully registered there is no exception or error but when the user signs out and reopen the app the app crashes . the logcat is basically pointing the error on this :
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener()
But if i change the currentUserID to Users .. the app stops crashing and runs smoothly but it doesnot loads up the username and the profile image that is located in the naviagation drawer.
mainactivity.java
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postlist;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private FirebaseUser FirebaseUser;
private DatabaseReference UsersRef;
private CircleImageView NavProfileImage;
private ImageButton AddNewPostButton;
private TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
AddNewPostButton = (ImageButton)findViewById(R.id.add_new_post_button);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View navView = navigationView.inflateHeaderView(R.layout.nav_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{ UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToPostActivity();
}
});
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent (MainActivity.this,PostActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
}
private void CheckUserExistance()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
sendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void sendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
after signout mFirebaseUser gets null value so this currentUserID value also gets null to avoid nullpointerexception do null check before you use currentUserID like below code
public class MainActivity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private RecyclerView postlist;
private Toolbar mToolbar;
private ActionBarDrawerToggle actionBarDrawerToggle;
private FirebaseAuth mAuth;
private FirebaseUser FirebaseUser;
private DatabaseReference UsersRef;
private CircleImageView NavProfileImage;
private ImageButton AddNewPostButton;
private TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
final FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mToolbar =(Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");
drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this,drawerLayout,R.string.drawer_open, R.string.drawer_close);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
AddNewPostButton = (ImageButton)findViewById(R.id.add_new_post_button);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
View navView = navigationView.inflateHeaderView(R.layout.nav_header);
NavProfileImage = (CircleImageView)navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
// replace below code
if (mFirebaseUser != null) {
UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{ if (dataSnapshot.hasChild("fullname")){
String fullname = dataSnapshot.child("fullname").getValue().toString();
NavProfileUserName.setText(fullname);
}if (dataSnapshot.hasChild("profileimage")) {
String image = dataSnapshot.child("profileimage").getValue().toString();
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}else {
Toast.makeText(MainActivity.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
sendUserToLoginActivity();
}
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item)
{ UserMenuSelector(item);
return false;
}
});
AddNewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SendUserToPostActivity();
}
});
}
private void SendUserToPostActivity() {
Intent addNewPostIntent = new Intent (MainActivity.this,PostActivity.class);
startActivity(addNewPostIntent);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
}
private void CheckUserExistance()
{
final String current_user_id = mAuth.getCurrentUser().getUid();
UsersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.hasChild(current_user_id)){
sendUserToSetupActivity();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendUserToSetupActivity() {
Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
setupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(setupIntent);
finish();
}
private void sendUserToLoginActivity()
{
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
OR you can check directly here also
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}else{
sendUserToLoginActivity();
}
I think you are getting null in currentUserId and then passing null to firebase. may be you are not getting user id make sure that user is logged in and then check that you are getting user id from firebase or not . if you are getting user id from firebase then try this .
UsersRef.child("Users").child(currentUserID).addValueEventListener(new
ValueEventListener(){ }
and make sure that all keys in your User Model class is public , i worked on firebase for about a month regularly and i faced many issues like this .
If you check I believe you don't have any logged in user that's why you are getting null value in currentUserID.
You are checking if user is logged in or not in OnStart(), you have to check that in onCreate() also. Because in activity lifecycle onCreate() is called before onStart().
Here is how your onCreate function should look:
#Override
protected void onCreate(Bundle savedInstanceState) {
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null)
{
sendUserToLoginActivity();
}else{
CheckUserExistance();
}
//Your code ...
}
You are getting java.lang.NullPointerException: Can't pass null for argument 'pathString' in child() because when you are signing out the user, you aren't sending him to a login activity and that's why this error. The simplest way to solve this is to use a listener. Let's assume you have two activities, the LoginActivity and the MainActivity. The listener that can be created in the LoginActivity should look like this:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
};
This basically means that if the user is logged in, skip the LoginActivity and go to the MainActivity.
Instantiate the FirebaseAuth object:
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
And start listening for changes in your onStart() method like this:
#Override
protected void onStart() {
super.onStart();
firebaseAuth.addAuthStateListener(authStateListener);
}
In the MainActivity, you should do the same thing:
FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
};
Which basically means that if the user is not logged in, skip the MainActivity and go to the LoginActivity. In this activity you should do the same thing as in the LoginActivity, you should start listening for changes in the onStart().
In this way, you'll never get an error like that again.
In my app a User can sign up and than sign in, after successfully signing in he's taken to an activity with events and stuff according to his preferences. I am able to sign up and sign in. But after signing when i can't get the current user from firebase auth. and am i signing in properly. I am new to android. All help will be appreciated.
The first code is loginactivity and the second one is where i am trying to get the uid.
public class LoginActivity extends AppCompatActivity {
FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference mdatabase;
private DatabaseReference fdatabase;
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
private EditText txtEmailLogin;
private EditText txtPassLogin;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener mAuthlistener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtEmailLogin = findViewById(R.id.EmailEditText);
txtPassLogin = findViewById(R.id.PassEditText);
firebaseAuth = FirebaseAuth.getInstance();
//controleert als er ingelogd moet worden of niet.
/* if (firebaseAuth.getCurrentUser() != null)
{
Intent i = new Intent(LoginActivity.this, Home.class);
i.putExtra("Email", firebaseAuth.getCurrentUser().getEmail());
startActivity(i);
}*/
}
public void btnregister_Click(View v) {
Intent i = new Intent(LoginActivity.this,RegisterActivity.class);
startActivity(i);
}
public void btnLogin_Click(View v){
ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this,"Please Wait...", "Processing...", true);
(firebaseAuth.signInWithEmailAndPassword(txtEmailLogin.getText().toString(), txtPassLogin.getText().toString()))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(LoginActivity.this ,"Login Succesfull" ,Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginActivity.this, Home.class);
startActivity(i);
}
else
{
Log.e("Error", task.getException().toString());
Toast.makeText(LoginActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
}
public class Home extends AppCompatActivity {
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
TextView txtUserNaam;
String uid,UserName;
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference mdatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mAuth=FirebaseAuth.getInstance();
mAuthListener=new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser().getUid() == null) {
//Your action here
Intent i = new Intent(Home.this, LoginActivity.class);
startActivity(i);
} else {
txtUserNaam = findViewById(R.id.txtusernaam);
mdatabase.child("USERS").child(firebaseAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserName = dataSnapshot.child("UserName").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
txtUserNaam.setText(UserName);
}
}
};
}
}
AuthStateListener is used to observe changes to the user's sign-in state. So you should have it in your LoginActivity
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
// intent call to second activity
}
}
}
You can bind you Listener to Auth in onStart() method like below
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
For getting the current logged in user details you can use
FirebaseAuth.getInstance().getCurrentUser().getUid();
this will return uid as a String.
Instead of declaring
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
Add this into your OnCreate
FirebaseUser mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
if (mCurrentUser != null) {
uid = mCurrentUser.getUid();
Then if you want you can declare your uid as public static String uid so that you would not have to rewrite the code and could just use the variable
uid