Populating a sub-group in firebase Database - android

I have an activity where i want to send a custom message to a sub-group in my database when a button is clicked. I tried to check for a user_id and send the message to those user id's, My problem is that when i click the button(status) it only sends that message to one person.
This is my Activity:
public class messageActivity extends AppCompatActivity {
private Button status;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String user_id;
private String message;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
gettingIntent();
status = (Button)findViewById(R.id.rescue);
status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
addUpdateMessage();
addTeamUpdateChat();
Toast.makeText(getApplicationContext(), "Team Update message was successfully sent",Toast.LENGTH_LONG).show();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Status");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
Toast.makeText(getApplicationContext(), "Logged in",Toast.LENGTH_SHORT).show();
}
}
private void gettingIntent() {
Intent intent =getIntent();
user_id = intent.getStringExtra("user_id");
}
private void addTeamUpdateChat() {
String current_user_ref="Team_Updates/"+mCurrentUserId+"/"+user_id;
String reciever_user_ref= "Team_Updates/"+user_id+"/"+mCurrentUserId;
DatabaseReference team_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = team_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " Is now a new Member of the team.");
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(reciever_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addUpdateMessage() {
mRootRef.child("Team_Updates_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Team_Updates_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Team_Updates_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
}
}
#Override
protected void onStop() {
super.onStop();
}
private void sendToStart() {
Intent startIntent = new Intent(messageActivity.this, Home.class);
startActivity(startIntent);
finish();
}
}
I'm Still learning Programming in Android Studio, Is there Any suggestions on how i should approach this?

You are sending a message only to single user because you are getting only a single user. To send a message to multiple users, you need to loop to get all those users and then send the message to all of them.

Related

How to allow users to change password before they logging in?

I would like to allow the users to change their password before logging in. In practice I have LoginActivity that with a clickable textview redirects to an activity where the user enters his email and the new password to be set. The problem is that when the user tries to log in, it fails. Is it possible to do this or do I have to change the method?
This is my code:
private EditText emailRetrieve, firstPassword, passwordConfirm;
private Button resetPasswordBtn;
private String email, password, passwordToConfirm = "";
private FirebaseAuth mAuth;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_password);
uploadUI();
mAuth = FirebaseAuth.getInstance();
resetPasswordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setNewPassword();
}
});
}
// Validation email and password
private boolean validation() {
boolean valid = true;
email = emailRetrieve.getText().toString();
password = firstPassword.getText().toString();
passwordToConfirm = passwordConfirm.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
emailRetrieve.setError("Insert valid email address");
valid = false;
} else {
emailRetrieve.setError(null);
}
if (password.isEmpty() || password.length() < 8) {
firstPassword.setError("Insert valid password");
valid = false;
} else {
firstPassword.setError(null);
}
if(passwordToConfirm.isEmpty() || (!passwordToConfirm.equals(password))) {
passwordConfirm.setError("Passwords must be equals");
valid = false;
} else {
passwordConfirm.setError(null);
}
return valid;
}
private String getPasswordToConfirm(TextView textView) {
String confirm = textView.getText().toString();
return confirm;
}
private void setNewPassword() {
if(!validation())
return;
Utils.loadProgressDialog(SetPasswordActivity.this, "Uploading...");
//progressBar.setVisibility(View.VISIBLE);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(datasnap.child("email").getValue().toString().equals(email)) {
datasnap.child("password").getRef().setValue(getPasswordToConfirm(passwordConfirm))
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(SetPasswordActivity.this, "Password successfully changed",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
#Override
public void uploadUI() {
emailRetrieve = findViewById(R.id.email_retrieve);
firstPassword = findViewById(R.id.first_password);
passwordConfirm = findViewById(R.id.password_confirm);
resetPasswordBtn = findViewById(R.id.reset_password_btn);
}
Thanks in advance to everyone!
I guess, you are navigating user to LoginActivity before the password is changed, Firebasedatabase call is asynchronous and you have to take user to LoginActivity only on Success, that is when you are showing toast to user. Basically move startActivity in setNewpassword to onSuccess of firebase query
private void setNewPassword() {
if(!validation())
return;
Utils.loadProgressDialog(SetPasswordActivity.this, "Uploading...");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(datasnap.child("email").getValue().toString().equals(email)) {
datasnap.child("password").getRef().setValue(getPasswordToConfirm(passwordConfirm))
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
Toast.makeText(SetPasswordActivity.this, "Password successfully changed",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
}

arrayList always loaded with user info from Firebase database regardless of which user is signed in?

In showdata method witch load FirebaseUser info when I run the app and signed in with any user , arrayList in the method is always loaded with User_03 info ,
debugging show that:
DataSnapshot ds is loaded with right value of signed in user ( right key and info ) .
uInfo ( the object which carry signed in user info) loaded with right data from database .
uInfo.setName(ds.getValue(UserInformations.class).getName()); = undefined .
I think there is something wrong in arryList size .
the attached screen shot I take it when arrive to breakpoint in line : toastMassege("it's Done") .
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist ;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo =new UserInformations();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " +
user.getEmail());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
ArrayList<String> arrayList=new ArrayList<>();
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
this is class UserInformations
class UserInformations {
public String email,name,phone_num ;
UserInformations() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
This is happening because you are have declared the ArrayList<String> arrayList=new ArrayList<>(); inside the for loop. This means that you are creating a new instance of ArrayList class every time you iterate.
In order to solve this, just move the decration outside for loop like this:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList=new ArrayList<>(); //Moved outside
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
int listSize = arrayList.size();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}
}

Load FirebaseUser info gives null value

In showdata method witch load FirebaseUser info I have null value for uInfo , I run the app and signed in with User_02 , debugging show that :
ds.getChild(userId ) reach to the right user who signed in and loaded with right key , but when try to get value from UserInformations.class gives me NullPointerException ,so what the mistake in the coade ?
I not that ds have key and value for User_01 . is that normal ?
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist ;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo =new UserInformations();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
uInfo.setName(ds.child(userId).getValue(UserInformations.class).getName()); // set the name
uInfo.setEmail(ds.child(userId).getValue(UserInformations.class).getEmail()); // set the Email
uInfo.setPhone_num(ds.child(userId).getValue(UserInformations.class).getPhone_num()); // set the PhonNum
ArrayList<String> arrayList =new ArrayList<>();
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter =new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,arrayList);
userInfolist.setAdapter(adapter);
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
UserInformation.java
class UserInformations {
private String Email,Name,Phone_num ;
UserInformations() {
}
String getEmail() {
return Email;
}
void setEmail(String email) {
this.Email = email;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
String getPhone_num() {
return Phone_num;
}
void setPhone_num(String phone_num) {
this.Phone_num = phone_num;
}
}
First, change your variables in UserInformations from private to public.
class UserInformations {
public String Email,Name,Phone_num ;
}
Second, you have to change your Firebase path from Phone number to Phone_num. Why? Well, that's because you are declaring String Phone_num inside the UserInformation.
Your current JSON:
{
"uid001": {
"Email": "user01#gmail.com",
"Name": "user01",
"Phone number": "0123456789"
},
"uid002": {
"Email": "user02#gmail.com",
"Name": "user02",
"Phone number": "0123456789"
},
}
Changed to below JSON:
{
"uid001": {
"Email": "user01#gmail.com",
"Name": "user01",
"Phone_num": "0123456789"
},
"uid002": {
"Email": "user02#gmail.com",
"Name": "user02",
"Phone_num": "0123456789"
},
}
When you used for(DataSnapshot ds : dataSnapshot.getChildren()) the ds already have the data of the child which is the user node no need for child(userId) do it directly :
uInfo.setName(ds.child("name").getValue());
uInfo.setEmail(ds.child("email").getValue());
uInfo.setPhone_num(ds.child("phone_num").getValue());

DataSnapshot get one user info every time

I receive FirebaseUser Id & email how signed in correctly as shown in debug screenshot , but DataSnapshot ds is always loaded with user_01 info , I tried hard to solve this problem and found Similar questions on the site but couldn't help . so can anyone help to solve this ?
public class AddToDatabase extends AppCompatActivity {
private static final String TAG = "AddToDatabase";
private ListView userInfolist;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
String userId;
UserInformations uInfo = new UserInformations();
DatabaseReference myRef;
FirebaseDatabase mFirebaseDatabase;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_to_database);
userInfolist = (ListView) findViewById(R.id.userInfolist);
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
user = mAuth.getCurrentUser();
userId = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMassege(" You are successfly signed in with " + user.getEmail());
} else {
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMassege(" You are successfly signed out ");
}
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
Boolean signedstate = true;
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (signedstate) {
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
signedstate = false;
}
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMassege(String massege) {
Toast.makeText(this, massege, Toast.LENGTH_SHORT).show();
}
}
this is class UserInformations :
class UserInformations {
public String email,name,phone_num ;
UserInformations() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
Your problem is that you are creating the adapter inside the for loop. In order to solve your problm, you need to move this line:
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
outside the for loop because you are creating a new instance of ArrayAdapter every time you iterate. Please use the following code:
private void showData(DataSnapshot dataSnapshot) {
ArrayList<String> arrayList = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if (signedstate) {
uInfo.setName(ds.getValue(UserInformations.class).getName());
uInfo.setEmail(ds.getValue(UserInformations.class).getEmail());
uInfo.setPhone_num(ds.getValue(UserInformations.class).getPhone_num());
arrayList.add(uInfo.getName());
arrayList.add(uInfo.getEmail());
arrayList.add(uInfo.getPhone_num());
signedstate = false;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
userInfolist.setAdapter(adapter);
toastMassege("its Done ");
}

Android Studio Firebase Database return null object reference

Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data
private void user_info(String user_id, String user_display_name) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Name",user_display_name);
userMap.put("Balls","30");
userMap.put("Level","1");
mProgressDialog.setMessage("Please Wait...");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}
else
Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
And how I try to retrieve the data
private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_acticity);
//Image
mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);
//Firebase
mUser = FirebaseAuth.getInstance().getCurrentUser();
String user_id = mUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
The toast don't show anything because it null
Change this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
to this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.

Categories

Resources