Android: Compare data between input and data retrieved from firebase - android

User data in firebase:
User class:
public User(String mName, String mEmail, String password, int mAge, String mGender) {
this.mName = mName;
this.mEmail = mEmail;
this.mAge = mAge;
this.mPassword=password;
this.mGender = mGender;
}
public String getPassword() {
return mPassword;
}
public String getEmail() {
return mEmail;
}
Retrieve user table:
#Override
protected void onStart() {
super.onStart();
mDataBase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
mUser = userSnapshot.getValue(User.class);
mUsers.add(mUser);
}
}
Then I was trying to validate email and password with input:
mEmail = (String) mEmailEt.getText().toString().trim().toLowerCase();
mPassword = (String) mPwdEt.getText().toString().trim().toLowerCase();
mLoginButton = findViewById(R.id.loginBtn);
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(mEmail, mPassword) == 1){
Intent intent = new Intent(getApplicationContext(),MainPage.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Login Failed", Toast.LENGTH_LONG).show();
}
}
});
public int validate(String email, String pwd) {
for (User user : mUsers) {
if (email.equals(user.getEmail().trim().toLowerCase()) && pwd.equals(user.getPassword().trim().toLowerCase())){
return 1;
}
}
return 0;
}
The problem is I did successfully retrieve the data, but I have no idea why the comparison always return 0. I cannot see any wrong here. Any answer would be a great help. Thanks!

Related

How to fix NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.rsolveapp.User.getEmail()'

I'm trying to retrieve data from current logged in user from my firebase realtime database, but when i go into activity that suppose to show the data, the app crash with the following error "java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.rsolveapp.User.getEmail()' on a null object reference"
This is the activity for showing the data
public class RsolverAccount extends AppCompatActivity {
TextView showEmail;
private static final String TAG = RsolverAccount.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rsolveraccount);
setWidget();
showData();
}
private void showData () {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if(firebaseUser != null) {
String email = firebaseUser.getEmail();
Log.d(TAG, email);
}
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
ValueEventListener postListener = new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
showEmail.setText(user.getEmail());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(postListener);
}
public void setWidget() {
showEmail = (TextView) findViewById(R.id.showEmail);
}
}
This is my User class
public class User implements Serializable{
private String email;
private String name, pass, id, phone;
private String key;
public User(){
}
public String getKey(){
return key;
}
public void setKey(String key){
this.key=key;
}
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 getPass(){
return pass;
}
public void setPass(String pass){
this.pass=pass;
}
public String getId(){
return id;
}
public void setId(String id){
this.id=id;
}
public String getPhone(){
return phone;
}
public void setPhone(String phone){
this.phone=phone;
}
#Override
public String toString(){
return " "+email+"/n"+
" "+name+"/n"+
" "+pass+"/n"+
" "+id+"/n"+
" "+phone;
}
public User(String Remail, String Rname, String Rpass, String Rid, String Rphone){
this.email=Remail;
this.name=Rname;
this.pass=Rpass;
this.id=Rid;
this.phone=Rphone;
}
}
This is my database structure
{
"description" : {
"-LpJNvsR3oIGA5pv1uOK" : {
"day" : "2",
"description" : "tes",
"eHour" : "12",
"eMin" : "12",
"sHour" : "12",
"sMin" : "12"
}
},
"userdesc" : {
"-LquV8N1AJbRdhSKMA2T" : {
"email" : "bryan5#gmail.com",
"id" : "870788464845",
"name" : "bry5",
"pass" : "123456",
"phone" : "484854484546"
}
}
}
This is how i insert the data
private void RegisterUser() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String emailUser = e1.getText().toString().trim();
String passwordUser = e3.getText().toString().trim();
String name1 = e2.getText().toString();
String id = e5.getText().toString();
String phone = e6.getText().toString();
if (emailUser.isEmpty()){
e1.setError("Email tidak boleh kosong");
}
// jika email not valid
else if (!Patterns.EMAIL_ADDRESS.matcher(emailUser).matches()){
e1.setError("Email tidak valid");
}
// jika password kosong
else if (passwordUser.isEmpty()){
e3.setError("Password tidak boleh kosong");
}
//jika password kurang dari 6 karakter
else if (passwordUser.length() < 6){
e3.setError("Password minimal terdiri dari 6 karakter");
}
else {
//create user dengan firebase auth
auth.createUserWithEmailAndPassword(emailUser,passwordUser)
.addOnCompleteListener(Register.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//jika gagal register do something
if (!task.isSuccessful()){
Toast.makeText(Register.this,
"Register gagal karena "+ task.getException().getMessage(),
Toast.LENGTH_LONG).show();
}
else {
//jika sukses akan menuju ke login activity
if(!isEmpty(e1.getText().toString()) && !isEmpty(e2.getText().toString()) && !isEmpty(e3.getText().toString()) && !isEmpty(e5.getText().toString())&& !isEmpty(e6.getText().toString())) {
submitUser(new User(e1.getText().toString(), e2.getText().toString(), e3.getText().toString(), e5.getText().toString(), e6.getText().toString()));
//Toast.makeText(this,"Wassup",Toast.LENGTH_SHORT).show();
/*startActivity(new Intent(MainActivity.this,MainActivity2.class));*/
//EditText etLocation = (EditText) findViewById(R.id.desc);
SharedPreferences sharedPref = getSharedPreferences("myuser", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("user", emailUser);
editor.apply();
Intent intent = new Intent(Register.this, MainActivity.class);
//intent.putExtra("location", etLocation.getText().toString());
startActivity(intent);
}
else{
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
e1.getWindowToken(), 0);
}
}
}
});
}
}
});
}
private boolean isEmpty(String s) {
return TextUtils.isEmpty(s);
}
private void submitUser(User user) {
database.child("userdesc").push().setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}
It seems like there is no valid User object in the data you're processing.
Your JSON is using push IDs for the child nodes under that, while your code is loading from FirebaseAuth.getInstance().getCurrentUser().getUid(). If you want to load the users by their UID, you should store them under their UID, with something like:
mDatabase = FirebaseDatabase.getInstance().getReference().child("sraboetapp").child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
mDatabase.setValue(user);
Based on the code you added to your question submitUser should be:
private void submitUser(User user) {
database.child("userdesc").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(user).addOnSuccessListener(this, new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
e1.setText("");
e2.setText("");
e3.setText("");
e4.setText("");
e5.setText("");
e6.setText("");
}
});
}

Is there something wrong and i get 0 as value from Firebase? [duplicate]

This question already has answers here:
How to return a list from Firestore database as a result of a function in Kotlin?
(3 answers)
Closed 3 years ago.
I m trying to take a value from firebase, and always i get "0". I check my code and i cant find any error.
I used the same code in another activity and i had the correct value. Now for no reason as i didnt made any change, in both activities i cant read the value that i need
Json file:
"Ranking" : {
"Aditi" : {
"avatarUrl" : "https://i.imgur.com/S9dkvBA.png",
"score" : 60,
"userClass" : "Wizard",
"userName" : "Aditi"
},
And my code:
//Method to get the userScore from Ranking table in firebase
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I expect the value of "60" but i get "0"
Update: Ranking class
public class Ranking {
private String userName;
private long score;
private String avatarUrl;
private String userClass;
public Ranking(String userName, long score, String avatarUrl, String userClass) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
this.userClass = userClass;
}
public Ranking() {
}
public Ranking(String userName, long score) {
this.userName = userName;
this.score = score;
}
public Ranking(String userName, long score, String avatarUrl) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
}
public String getUserClass() {
return userClass;
}
public void setUserClass(String userClass) {
this.userClass = userClass;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
just add child("Aditi") in reference :-
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking").child("Aditi");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Registration Page does not record user data with Firebase

public class RegisterActivity extends AppCompatActivity {
//create variables
private EditText mUsername, mPassword, mEmail, mPhone;
private Button mRegister;
private TextView mLogin;
private FirebaseAuth mAuth;
private ImageView mProfilePicture;
String user_email, user_name, user_phone, user_password;
//on creation of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupViews();
//firebase instance declared
mAuth = FirebaseAuth.getInstance();
//When register is clicked
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if all fields are okay using validation method
if(validate()){
//get user info
String user_email = mEmail.getText().toString().trim();
String user_password = mPassword.getText().toString().trim();
String user_phone = mPhone.getText().toString().trim();
String user_name = mUsername.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
sendEmailVerification();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//Return user back to login page
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
});
}
//setup views by id from xml
private void setupViews(){
mUsername = (EditText)findViewById(R.id.editTextNewUsername);
mPassword = (EditText)findViewById(R.id.editTextNewPassword);
mEmail = (EditText)findViewById(R.id.editTextNewEmail);
mPhone = (EditText)findViewById(R.id.editTextPhone);
mRegister = (Button)findViewById(R.id.buttonRegister);
mLogin = (TextView)findViewById(R.id.textViewLogin);
mProfilePicture = (ImageView)findViewById(R.id.imageViewProfilePicture);
}
//validate if all fields are okay and not empty
private Boolean validate() {
Boolean result = false;
//convert inputs to strings
String user_name = mUsername.getText().toString();
String user_password = mPassword.getText().toString();
String user_email = mEmail.getText().toString();
String user_phone = mPhone.getText().toString();
//check if any fields are empty, if not then return result
if (user_name.isEmpty() || user_password.isEmpty() || user_email.isEmpty() || user_phone.isEmpty()) {
Toast.makeText(this, "All fields are required for registration.", Toast.LENGTH_SHORT).show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegisterActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
mAuth.signOut();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(mAuth.getCurrentUser().getUid());
UserProfile userProfile = new UserProfile(user_phone, user_email, user_name);
myRef.setValue(userProfile);
}
}
Solved the crash with my profile page and got it to save artifical data, but found out my registration page is the problem and is not recording data. Here is my Userprofile.java for reference
public class UserProfile {
public String user_phone;
public String user_email;
public String user_name;
public UserProfile() {
}
public UserProfile(String user_phone, String user_email, String user_name) {
this.user_phone = user_phone;
this.user_email = user_email;
this.user_name = user_name;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
Any help would be appreciated, i'd read extensively on the topic and can't seem to see whatever small issue is causing the hold-up. Any other pointers are also welcome.
Try changing:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
assert userProfile != null;
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
With:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
if(userProfile != null){
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
}

Firebase DataSnapshot Null values

My app allows you to add a Player to a node, once they have been added I am using the below method to search by phoneNum to see if that player exists in the 'users' node.
Where I am having trouble is that I need to be able to access the values from the datasnapshot for the user within the found matching node. e.g.return the value of the user id. When I attempt this it keeps showing as a null value and when I try to log to the console it complains that it is a null value which doesn't make sense as the if statement should take care of this.
The method is able to find if a player exists in the the users node and displays a Toast message to indicate this.
Code:
public void checkPlayerNum(final String phoneNum) {
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
String uId = mUser.getUid();
// Log.d("TAG",uId);
Toast.makeText(getApplicationContext(), "* found **"+ uId , Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
final Query query = mFirebaseDatabase.orderByChild("phoneNum").equalTo("userPhoneNumber");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//here means the value exist
//do whatever you want to do
} else {
//here means the value not exist
//do whatever you want to do
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Use this to check whether the data exist or not.
you need to do this at two steps , first check if the user exists. then you get user info by your userId.
DatabaseReference mDatabaseReference;
public void checkPlayerNum(final String phoneNum,final String userId) {
mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
if (!TextUtils.isEmpty(phoneNum)) {
final Query phoneNumReference = mDatabaseReference.orderByChild("phoneNum").equalTo(phoneNum);
ValueEventListener phoneNumValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
// user exists
getUserInf(userId);
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumReference.addListenerForSingleValueEvent(phoneNumValueEventListener);
} else {
Log.e("Error","phoneNum is null");
}
}
get user info by userId. mDatabaseReference is the same as before . define it as member field .
void getUserInf(String userId) {
userValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// get user data
User mUser = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabaseReference.child(userId).addListenerForSingleValueEvent(userValueEventListener);
}
your user Pojo should be like below.
public class User {
String email,name,phoneNum,uid;
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 getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
}
Thanks everybody I managed to achieve it by using childEventListener
public void checkingNumber(final String phoneNum){
DatabaseReference mDatabaseReference =
FirebaseDatabase.getInstance().getReference().child("users");
final Query query = mDatabaseReference;
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
// String key = String.valueOf(dataSnapshot.getValue());
User mUser = dataSnapshot.getValue(User.class);
// String uId = mUser.getUid();
// usersDatabase.child(mUser.getUid());
// Log.d("TAG",uId);
if(mUser.getPhoneNum().equals(phoneNum)) {
String uId= mUser.getUid();
String email = mUser.getEmail();
String name = mUser.getName();
Toast.makeText(getApplicationContext(), "* found **" + " " + uId + " " + " " + email + " " + name, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "****NOT FOUND****", Toast.LENGTH_LONG).show();
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

How to get the value of child node in firebase

My Firebase heirarchy
I want to get the value of all "user", but calling datasnapshot.getValue is returning null.
FirebaseDatabase.getInstance().getReference("data").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
if (dataSnapshot.getKey().equals("user"))
username = data.getValue().toString();
Toast.makeText(getApplicationContext(), "sender is " + username, Toast.LENGTH_SHORT).show();
}
}
Create a class with the database structure.
public class Data {
private String msgbody;
private String mtime;
private String uname;
private String user;
public Data() {
}
public String getMsgbody() {
return msgbody;
}
public void setMsgbody(String msgbody) {
this.msgbody = msgbody;
}
public String getMtime() {
return mtime;
}
public void setMtime(String mtime) {
this.mtime = mtime;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
then
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Data obj = snapshot.getValue(snapshot.getValue(Data.class);
}

Categories

Resources