image of database structure
code for database structure
I am trying to retrieve the profile image and username that is saved by the user during the registration process in the navigation header. Here is something that I did . At first I tried to get string current user but it showed me null pointer exception then I tried with if statement and changed the child from current user id to Users , it only solved the null pointer but this didn't retrive the data from firebase.
MainActivity.java
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.Picasso;
import de.hdodenhof.circleimageview.CircleImageView;
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 TextView NavProfileUserName;
String currentUserID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FirebaseUser mFirebaseUser = mAuth.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
mAuth = FirebaseAuth.getInstance();
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);
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("profileimages")) {
String image = dataSnapshot.child("profileimages").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;
}
});
}
#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();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
private void UserMenuSelector(MenuItem item)
{
switch (item.getItemId())
{
case R.id.nav_home:
Toast.makeText(this,"Home",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_post:
break;
case R.id.nav_Profile:
Toast.makeText(this,"profile",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_find_friends:
Toast.makeText(this,"frns",Toast.LENGTH_SHORT).show();
break;
case R.id.nav_logout:
mAuth.signOut();
sendUserToLoginActivity();
break;
}
}
}
I use the glide for loading images from firebase. It would be something like this:
import com.bumptech.glide.Glide;
UserModel userModel = new UserModel;
Glide.with(YourActivity.this)
.load(userModel.getUser_image())
.into(user_image);
For more info please look at the github repository.
After seeing your database structure I believe that the child inside Users node is the UID of current firebase user and in the Users node if you are trying to fetch user details of current user then your query should be like this
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
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("profileimages")) {
String image = dataSnapshot.child("profileimages").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) {
}
});
At the time of register the user you should save the user's info like this
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
userModel.setUserid(user.getUid());
userModel.setMobile("120xxxxxxxx");
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName("Some Name")
.setPhotoUri("Phot url of the user")
.build();
user.updateProfile(profileUpdates);
Then when you want to retrive the image from the user's info with the other info's too....
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
headerResult = new AccountHeaderBuilder()
.withActivity(MainActivity.this)
.withHeaderBackground(R.drawable.gradient_home_background)
.addProfiles(
new ProfileDrawerItem().withName(user.getDisplayName()).withEmail(user.getPhoneNumber()).withIcon(user.getPhotoUrl())
)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
} else {
headerResult = new AccountHeaderBuilder()
.withActivity(MainActivity.this)
.withHeaderBackground(R.drawable.gradient_home_background)
.withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
#Override
public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) {
return false;
}
})
.build();
}
I see, you did use mAuth before initializing it! So it is returning null.
FirebaseUser mFirebaseUser = **mAuth**.getCurrentUser();
if (mFirebaseUser != null) {
currentUserID = mFirebaseUser.getUid();
}
**mAuth = FirebaseAuth.getInstance();**
Move mAuth = FirebaseAuth.getInstance(); line just before FirebaseUser mFirebaseUser = mAuth.getCurrentUser(); line
Related
I cannot log in to my application, and I found no error in the codes. It keeps showing, email is required every time I tried to log in. I connect this app with FireStore as well. So, I need help what did I did wrong here because it supposed to go to the main activity after my login page:
public class Login extends AppCompatActivity {
EditText mPassword,mEmail;
FirebaseAuth auth;
Button mlogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_user);
final TextView register = findViewById(R.id.register_txt);
mPassword = findViewById(R.id.password_et);
mEmail = findViewById(R.id.email_et);
mlogin = findViewById(R.id.login_bt);
auth = FirebaseAuth.getInstance();
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() < 6) {
mPassword.setError("6 or more character long");
return;
}
auth.signInWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(Login.this,"Login",Toast.LENGTH_SHORT)
.show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
} else {
Toast.makeText(Login.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
}
}
This is my register, firebase auth, and firestore connected to get information on the users.
public class Register extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mfullname, mPassword, mphoneNo, mEmail;
TextView register;
FirebaseAuth auth;
FirebaseFirestore fstore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register_user);
final TextView login = findViewById(R.id.login_text);
register = findViewById(R.id.register_bt);
mEmail = findViewById(R.id.email_et);
mPassword = findViewById(R.id.password_et);
mfullname = findViewById(R.id.fullname_et);
mphoneNo = findViewById(R.id.phoneNum_et);
auth = FirebaseAuth.getInstance();
fstore = FirebaseFirestore.getInstance();
if(auth.getCurrentUser() != null)
{
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String fullName = mfullname.getText().toString();
String phoneNo = mphoneNo.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password is required");
return;
}
if(password.length() <6){
mPassword.setError("6 or more character long");
return;
}
auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Register.this,"User Created",Toast.LENGTH_SHORT).show();
userID = auth.getCurrentUser().getUid();
DocumentReference documentReference = fstore.collection("Users").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("fName",fullName);
user.put("email",email);
user.put("phone",phoneNo);
documentReference.set(user).addOnSuccessListener(aVoid -> {
Log.d(TAG, "onSuccess: user profile is created for" + userID);}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: " + e.toString());
}
});
startActivity(new Intent(getApplicationContext(),Login.class));
} else {
Toast.makeText(Register.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Login.class));
}
});
}
}
MainActivity class:
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<HomeModel> homeModel;
MainAdapter mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).addToBackStack(null).commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
selectedFragment = new HomeFragment();
break;
case R.id.navigation_dashboard:
selectedFragment = new DashboardFragment();
break;
case R.id.navigation_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.navigation_profile:
selectedFragment = new ProfileFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).addToBackStack(null).commit();
return true;
}
};
}
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
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.
I am working on a Booking App ,where there are different time slots in a day(for example 11:30,12:30) in which users can book their ride.But I don't want the booking option to be open for the whole day,it should just be open from a certain time until the next day.I've heard this can be done by cloud functions,if so ,can anyone tell me how?
This is my BookingActivity.java
public class BookingActivity extends AppCompatActivity {
private DatabaseReference mUser;
private DatabaseReference mTime1;
private DatabaseReference mTime2;
private DatabaseReference mCount1;
private DatabaseReference mCount2;
private FirebaseAuth mAuth;
private static final String TAG = "BookingActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_booking);
mAuth = FirebaseAuth.getInstance();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FirebaseUser fu = mAuth.getCurrentUser();
final User newUser = new User(fu);
mUser = FirebaseDatabase.getInstance().getReference().child("Users");
mTime1 = FirebaseDatabase.getInstance().getReference().child("3:30");
mTime2 = FirebaseDatabase.getInstance().getReference().child("5:30");
mCount1 = FirebaseDatabase.getInstance().getReference().child("Count#3:30");
mCount2 = FirebaseDatabase.getInstance().getReference().child("Count#5:30");
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Update(mTime1,mCount1,newUser);
}
});
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Update(mTime2,mCount2,newUser);
}
});
}
public void Book(DatabaseReference mDatabase,User user) {
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
HashMap<String,String>datamap = new HashMap<>();
if(user!=null) {
datamap.put("Name", user.getUserName());
datamap.put("Email", user.getUserEmail());
datamap.put("timestamp",ts);
datamap.put("Limit", user.setRating("1"));
}
mDatabase.push().setValue(datamap);
}
public void Update(final DatabaseReference mDatabase, DatabaseReference mref,final User user) {
mref.runTransaction(new Transaction.Handler() {
#NonNull
#Override
public Transaction.Result doTransaction(#NonNull MutableData mutableData) {
Integer CurrentValue = mutableData.getValue(Integer.class);
if(CurrentValue==null) {
return Transaction.success(mutableData);
}
else if(CurrentValue<5 && user.getRating().equals("0")){
mutableData.setValue(CurrentValue + 1);
Book(mDatabase,user);
runOnUiThread(new Runnable() {
public void run() {
final Toast toast = Toast.makeText(BookingActivity.this,"Booked Successfully",Toast.LENGTH_SHORT);
toast.show();
}
});
}
else{
runOnUiThread(new Runnable() {
public void run() {
final Toast toast = Toast.makeText(BookingActivity.this,"Maximum Limit Reached",Toast.LENGTH_SHORT);
toast.show();
}
});
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(#Nullable DatabaseError databaseError, boolean b, #Nullable DataSnapshot dataSnapshot) {
Log.d(TAG, "Updating likes count transaction is completed");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuLogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
}
return true;
}
My database structure looks like this
You check the time and enable/disable the booking button based on it when your activity starts. Put a similar check inside the booking activity so they can't launch it directly.
Such feature doesn't exist on Google Cloud Functions. You may be referring to scheduling[1], but that is used to trigger calls to functions.
What you can do is implement that business logic into the function itself, leaving it always available on the HTTP level, but only having it actually book something at certain hours (get the current time with "new Date();").
Cheers,
Miguel
[1] https://medium.com/google-cloud/google-cloud-functions-scheduling-cron-5657c2ae5212
I am very new to firebase and I am unable to fetch the content of the key value. I tried out few things but all were unsuccessful.
Can anyone help me out in fetching the data please?
My firebase database - Firebase Database Structure:
My code -
public class Dashboard extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Toolbar dashboard_toolbar;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mActionBarDrawerToggle;
private FirebaseAuth mAuth;
DatabaseReference rootRef, teacher, teacherPost;
String str;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
/* str = (String) getIntent().getExtras().get("temp");*/
textView = (TextView) findViewById(R.id.institute_news);
mAuth = FirebaseAuth.getInstance();
dashboard_toolbar = (Toolbar) findViewById(R.id.dashboard_toolbar);
setSupportActionBar(dashboard_toolbar);
getSupportActionBar().setTitle("Dashboard");
dashboard_toolbar.setTitleTextColor(0xFFFFFFFF);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawable);
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, dashboard_toolbar, R.string.open, R.string.close);
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mDrawerLayout.addDrawerListener(mActionBarDrawerToggle);
mActionBarDrawerToggle.syncState();
dashboard_toolbar.post(new Runnable() {
#Override
public void run() {
Drawable d = ResourcesCompat.getDrawable(getResources(), R.drawable.actionmenu, null);
dashboard_toolbar.setNavigationIcon(d);
}
});
NavigationView navigationView = (NavigationView) mDrawerLayout.findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
rootRef = FirebaseDatabase.getInstance().getReference();
teacher = rootRef.child("admin").child("classPost");
teacherPost = teacher.child("post");
String mGroupId = teacherPost.push().getKey();
Toast.makeText(this, "" + teacherPost, Toast.LENGTH_SHORT).show();
textView.setText(mGroupId);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.nav_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mActionBarDrawerToggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.aboutUs) {
} else if (id == R.id.help) {
} else if (id == R.id.report) {
} else if (id == R.id.logoutmenu) {
mAuth.signOut();
sendToStart();
} else if (id == R.id.setting) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawable);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void getAttendance(View view) {
Toast.makeText(this, "Attendance Details Apk Fire here", Toast.LENGTH_LONG).show();
}
public void trackChild(View view) {
Toast.makeText(this, "child tracker apk fire here Here", Toast.LENGTH_LONG).show();
}
public void getEwallet(View view) {
Toast.makeText(this, "Ewallet Apk Fire Here", Toast.LENGTH_LONG).show();
}
public void getHealth(View view) {
Toast.makeText(this, "Health apk fire here", Toast.LENGTH_LONG).show();
}
public void getMessageBoardDetails(View view) {
startActivity(new Intent(this,MessageBoard.class));
}
public void startChat(View view) {
startActivity(new Intent(this,Chat.class));
}
private void sendToStart() {
startActivity(new Intent(Dashboard.this,Start.class));
finish();
}
public void readMore(View view) {
startActivity(new Intent(this,InstituteMessageBoard.class));
}
}
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
String retrieveposts=data.child("posts").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'am assuming you want the post's values inside the classPost.
Explaining the code:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("admin").child("classPost");
The above is a reference to the location in the database. So child("admin").child("classPost"). You are referring to the location of the node classPost that is under the node admin, thus using child(node_name).
Now this:
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data : dataSnapshot.getChildren()){
String retrieveposts=data.child("posts").getValue().toString();
}
}
is a listener to be able to retrieve the values from the database. dataSnapshot here is the classPost. So when you write dataSnapshot.getChildren() it means you are getting the children of classPost and then data will iterate inside the children thus giving you the values of posts
To achieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classPostRef = rootRef.child("admin").child("classPost");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String post = ds.child("post").getValue(String.class);
Log.d("TAG", post);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
classPostRef.addListenerForSingleValueEvent(eventListener);