App Stopped - Retriving data from firebase - android

I don't know whats wrong with the code..
when I enter the information , my app shows - unfortunately stopped.
To access the both zone , I have declared the String at the top.
IDE also doesn't show any error.
I have also followed some answers from stackoverflow but , the error remains the same.
I want to retrieve data from here
My code is -
public class LoginPage extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef;
String name, password, email, edtName, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
final EditText uname, pass;
Button login, signup;
uname = (EditText) findViewById(R.id.editUsername);
pass = (EditText) findViewById(R.id.editPassword);
login = (Button) findViewById(R.id.buttonLogin);
signup = (Button) findViewById(R.id.buttonSignup);
edtName = uname.getText().toString();
edtPassword = pass.getText().toString();
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(LoginPage.this, "Button Tapped", Toast.LENGTH_SHORT).show();
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("sampBase");
DatabaseReference zone1Ref = zonesRef.child(name);
DatabaseReference zone1NameRef = zone1Ref.child("Name");
DatabaseReference zone1PassRef = zone1Ref.child("Password");
// name retrive
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
name = dataSnapshot.getValue(String.class);
Toast.makeText(LoginPage.this, name+" is name", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
// password retrive
zone1PassRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
password = dataSnapshot.getValue(String.class);
if(password != edtPassword){
Toast.makeText(LoginPage.this, "Wrong password.!", Toast.LENGTH_SHORT).show();
pass.setText("");
return;
}
else{
Toast.makeText(LoginPage.this, "Login Successful.!", Toast.LENGTH_SHORT).show();
Intent i = new Intent(LoginPage.this, HomePage.class);
i.putExtra("Name", name);
startActivity(i);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}

You haven't assigned asharfulais value to name variable.
As I have read your code, I couldn't notice the assignment. If I am correct, your name is null, and you cannot pass null to child() method.
You can fix this by simply assigning the value before getting any further (deeper) refereences.
name ="asharfulais";
Notes:
As your app could have more users, you should consider retrieving user's ID's rather than declaring their usernames.
It's good practice to declare string variables (children names in database) that never change as constants in a separate class (E.g. Constants.java).

Related

Can't pass null for argument 'pathString' in child() at com.google.firebase.database.DatabaseReference.child(Unknown Source:40) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am creating an android app to login the users by using Mobile number OTP verification from fire-base This is how the database looks like
This is the loggin activity where i am passing the value "mobile" to OTP typing activity( here LoginActivity.java)
CardView card_view = findViewById(R.id.cardView);
card_view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobile = editTextMobile.getText().toString().trim();
if(mobile.isEmpty() || mobile.length() < 10){
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
if(mobile.length()>10)
{
editTextMobile.setError("Enter a valid mobile");
editTextMobile.requestFocus();
return;
}
Intent intent = new Intent(LoginActivity.this, VerifyPhoneActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
}
});
This is where user will enter the OTP (VerifyPhoneActivity.java). If the OTP is correct and if the mobile number is not exist in database already then user can go to sigh up up activity
public FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth= FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance().getReference();
sendVerificationCode();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
verifySignInCode();
}
});
}
private void verifySignInCode()
{
final EditText fd = (EditText) findViewById(R.id.et1);
String value= fd.getText().toString();
final EditText sd = (EditText) findViewById(R.id.et2);
String value1= sd.getText().toString();
// int finalValue1=Integer.parseInt(value1);
EditText td = (EditText) findViewById(R.id.et3);
String value2= td.getText().toString();
EditText fod = (EditText) findViewById(R.id.et4);
String value3= fod.getText().toString();
EditText fid = (EditText) findViewById(R.id.et5);
String value4= fid.getText().toString();
EditText sid = (EditText) findViewById(R.id.et6);
String value5= sid.getText().toString();
code = value + value1+value2+value3+value4+value5;
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(codesent, code);
signInWithPhoneAuthCredential(credential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref.child("Users");
ref.child(mobile).child(uid);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "already account there",
Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(VerifyPhoneActivity.this, Signup.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
Intent myIntent = new Intent(VerifyPhoneActivity.this, Signup.class);
startActivity(myIntent);
Toast.makeText(getApplicationContext(), "account not exist",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(getApplicationContext(), "login success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "login faild",
Toast.LENGTH_LONG).show();
// Sign in failed, display a message and update the UI
// Log.w(TAG, "signInWithCredential:failure", task.getException());
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
// The verification code entered was invalid
Toast.makeText(getApplicationContext(), "OTP was wrong",
Toast.LENGTH_LONG).show();
}
}
}
});
}
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks=new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
Toast.makeText(getApplicationContext(), "verification completed",
Toast.LENGTH_LONG).show();
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(getApplicationContext(), "sending faild"+e,
Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
// super.onCodeSent(s, forceResendingToken);
Toast.makeText(getApplicationContext(), "sent",
Toast.LENGTH_LONG).show();
codesent=s;
}
};
private void sendVerificationCode() {
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
Toast.makeText(getApplicationContext(), mobile,
Toast.LENGTH_LONG).show();
String phonenumber= "+91"+mobile;
// Toast.makeText(getApplicationContext(), phonenumber,
// Toast.LENGTH_LONG).show();
PhoneAuthProvider.getInstance().verifyPhoneNumber(
phonenumber, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
this, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
}
And at last this is where (Signup.java) am getting error (i will mension below)
public class Signup extends Activity {
String name;
String address;
String pincode;
String city;
String mobile;
DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Intent intent = getIntent();
mobile = intent.getStringExtra("mobile");
findViewById(R.id.signupbutton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText nameedittext = (EditText) findViewById(R.id.nametextview);
name= nameedittext.getText().toString();
EditText addressedittext = (EditText) findViewById(R.id.addresstextview);
address= addressedittext.getText().toString();
EditText pincodeedittext = (EditText) findViewById(R.id.picodetextview);
pincode= pincodeedittext.getText().toString();
EditText cityedittext = (EditText) findViewById(R.id.citytextview);
city= cityedittext.getText().toString();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref = ref.child("Users");
FirebaseUser userid = FirebaseAuth.getInstance().getCurrentUser();
final String uid = userid.getUid();
ref = ref.child(mobile).child(uid);
Map<String, String> userData = new HashMap<String, String>();
userData.put("Name", name);
userData.put("Address", address);
userData.put("Pin", pincode);
userData.put("City", city);
ref.setValue(userData);
}
});
}
}
I am facing 2 problems
I am getting the error below and app crashes app relaunching the same activity (Signup.java) if i enter the details again it will get updated in db as screenshot above (in case i am the first user)
If the first user signed up and his mobile got registered then when the second user sign up it is showing "login success" and account "already there" 2 toasts
Error am getting
2019-03-15 16:57:40.706 1932-1932/com.example.meenvandi E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.meenvandi, PID: 1932
java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()
at com.google.firebase.database.DatabaseReference.child(Unknown Source:40)
at com.example.meenvandi.Signup$1.onClick(Signup.java:78)
at android.view.View.performClick(View.java:6330)
at android.view.View$PerformClick.run(View.java:25136)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:192)
at android.app.ActivityThread.main(ActivityThread.java:6778)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:875)
I am just starting android and this project is very very impotent for me please help if i you can identify the problem which i am unable to
One of the variables are null, its either mobile or uid, you can try to print both variables out to know which one is null.
My guess is you are trying to save a user in the db and this user haven't logged in to firebase before so uid will be null

Trying to store email address as a key in firebase database but getting this error: [duplicate]

This question already has answers here:
Validate username and email crashed and cannot insert to firebase database
(2 answers)
Closed 4 years ago.
I want to store email address and password into firebase, and i wish to store email address as primary key but the app crash and show :
Invalid Firebase Database path: ccw#qq.com. Firebase Database paths
must not contain '.', '#', '$', '[', or ']'
private DatabaseReference Userdatabase;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private static final String TAG = "SignupActivity";
EditText nameText, addressText, emailText, mobileText, passwordText, reEnterPasswordText;
Button signupButton;
TextView loginLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
nameText = (EditText) findViewById(R.id.input_name);
addressText = (EditText) findViewById(R.id.input_address);
emailText = (EditText) findViewById(R.id.input_email);
mobileText = (EditText) findViewById(R.id.input_mobile);
passwordText = (EditText) findViewById(R.id.input_password);
reEnterPasswordText = (EditText) findViewById(R.id.input_reEnterPassword);
firebaseAuth = FirebaseAuth.getInstance();
signupButton = (Button) findViewById(R.id.btn_signup);
loginLink = (TextView) findViewById(R.id.link_login);
Userdatabase = FirebaseDatabase.getInstance().getReference("User");}
public void AddUser(final String UserEmail, final String Username, final String Password,
final String PhoneNumber, final String ComfirmPassword
, final String Address) {
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(UserEmail);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
Log.i(TAG, "Username : " + Username + " Had Already Exist");
Toast.makeText(getApplicationContext(), "Username Exist !", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
return;
}
});
firebaseAuth.createUserWithEmailAndPassword(UserEmail,Password).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (!task.isSuccessful()) {
Log.i(TAG, "Buyer FirebaseAuth Register : Fail");
Toast.makeText(getApplicationContext(), "Could Not Register Your Account", Toast.LENGTH_SHORT).show();
return;
}
else
{
Log.i(TAG, "Buyer FirebaseAuth Register : Success");
Userdatabase = FirebaseDatabase.getInstance().getReference("User").child(UserEmail);
final User user = new User(UserEmail, Password, Username, PhoneNumber, Address, ComfirmPassword);
Userdatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
Userdatabase.setValue(user);
Log.i(TAG, "FirebaseDatabase Add Buyer : Success");
Toast.makeText(getApplicationContext(), "Register Complete", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.w(TAG, "Database Error");
}
});
}
}});
}
Or firebase really not allow us to store email address as a primary key?
No you cannot use special characters in your key value because it will break the functionalities of Firebase (especially the auto-built REST API).
If your tree has a node that contains a / in it's key, trying to access it via the REST API will be ambiguous :
http://yourproject.firebase.com/customers/mike/123
Does it mean the property 123 from mike ? Or is it the node that has mike/123 as key ? Impossible to know ...
You should rely on auto-generated IDs for your customer node, and then store the email address in a field of this node :
users
- h0r6TNCkEjMBGnYauwOdXhWt6oD3
- email:mike#example.com

Firebase: Add to Authenticated User

Please help, Can I add values to my authenticated user?
I have a createUser class where I have created my authenticated user.
public class CreateUserAccount extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private Button btnSignUp;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
Toast.makeText(this, "Please turn on usage access for this app", Toast.LENGTH_LONG).show();
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
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;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password is too short. Please enter a minimum of 6 characters", Toast.LENGTH_SHORT).show();
return;
}
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateUserAccount.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(CreateUserAccount.this, "User Account Created" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
// 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.
if (!task.isSuccessful()) {
Toast.makeText(CreateUserAccount.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(CreateUserAccount.this, LandingPage.class));
finish();
}
}
});
}
});
}
}
After the authenticated user has logged in, they can click on a page where they can input their children's names, which are written to a realtime DB.
public class AddChild extends AppCompatActivity {
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
String useruid=user.getUid();
//we will use these constants later to pass the artist name and id to another activity
public static final String ARTIST_NAME = "net.simplifiedcoding.firebasedatabaseexample.artistname";
public static final String ARTIST_ID = "net.simplifiedcoding.firebasedatabaseexample.artistid";
//view objects
EditText editChildName;
CardView addChild;
ListView lvChildren;
//a list to store all the artist from firebase database
List<Child> children;
//our database reference object
DatabaseReference databaseChildren;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_child);
//getting the reference of artists node
databaseChildren = FirebaseDatabase.getInstance().getReference("children");
//getting views
editChildName = (EditText) findViewById(R.id.editChildName);
lvChildren = (ListView) findViewById(R.id.lvChildren);
addChild = (CardView) findViewById(R.id.addChild);
//list to store artists
children = new ArrayList<>();
//adding an onclicklistener to button
addChild.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//calling the method addArtist()
//the method is defined below
//this method is actually performing the write operation
addChild();
}
});
}
/*
* This method is saving a new artist to the
* Firebase Realtime Database
* */
private void addChild() {
//getting the values to save
String name = editChildName.getText().toString().trim();
//checking if the value is provided
if (!TextUtils.isEmpty(name)) {
//getting a unique id using push().getKey() method
//it will create a unique id and we will use it as the Primary Key for our Artist
String id = databaseChildren.push().getKey();
//creating an Artist Object
Child child = new Child(name);
//Saving the Artist
databaseChildren.child(id).setValue(child);
//setting edittext to blank again
editChildName.setText("");
//displaying a success toast
Toast.makeText(this, "Child added", Toast.LENGTH_LONG).show();
} else {
//if the value is not given displaying a toast
Toast.makeText(this, "Please enter a name", Toast.LENGTH_LONG).show();
}
}
}
______CHILD CLASS________
import com.google.firebase.database.IgnoreExtraProperties;
#IgnoreExtraProperties
public class Child {
private String childName;
public Child(){
//this constructor is required
}
public Child(String childName) {
this.childName = childName;
}
public String getChildName() {
return childName;
}
}
Is there any way of adding the addChild class db values that I have inputted to this user?
So that the authenticated user can view their children names that have been inputted? thanks
Thanks
yes, after you authenticate your user you should get your users Auth ID
if your user is succefully logged into your app you should do this to put childs inside your user
private FirebaseAuth mAuth;
String userID;
// ...
mAuth = FirebaseAuth.getInstance();
userID = mAuth.getCurrentUser().getUid();
after that , where you are posting your addChildren class you should call your user to succefully add data to the auntheticated user
mDatabase.child(userID).child("Name").setValue("Robert");
thats an example on how to add data inside your auth users.
where mDatabase is your database reference like this
mDatabase = FirebaseDatabase.getInstance().getReference();
happy coding

User login can'd identify user position

User register as student or tutor during registration which saved in firebase database but when login cannot identify the user position which saved in the firebase database so what should I do? Please anyone can give suggestion or advice me how to do this.
The database is save the uid from email authentication as the node under the root then rest details is the children of the uid.
The code like this
private FirebaseAuth auth;
private EditText un, pw;
private String getun, getpw, uid;
private Button bl;
private FirebaseDatabase db;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
uid = auth.getCurrentUser().getUid();
ref = db.getReference("users").child(uid);
un = (EditText) findViewById(R.id.Lun);
pw = (EditText) findViewById(R.id.Lpw);
bl = (Button) findViewById(R.id.Lbt);
final TextView rl = (TextView) findViewById(R.id.Lreg);
//login
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getun = un.getText().toString().trim();
getpw = pw.getText().toString().trim();
loginaction(getun, getpw);
}
});
//open register page
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ri = new Intent(Login.this,Register.class);
Login.this.startActivity(ri);
}
});
}
private void loginaction(String a, String b){
auth.signInWithEmailAndPassword(a, b).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "Login Success" + task.isSuccessful());
if (!task.isSuccessful()) {
Log.w("Login", "Login Failed", task.getException());
Toast.makeText(Login.this, "Login Failed. Please try again", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
ref.orderByChild("position").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ps = dataSnapshot.getValue().toString();
if(ps.equalsIgnoreCase("student")){
Intent i = new Intent(Login.this, StudentHomePage.class);
startActivity(i);
}else if (ps.equalsIgnoreCase("tutor")){
Intent i = new Intent(Login.this, TutorHomePage.class);
startActivity(i);
}else{
Toast.makeText(Login.this,
"Wrong input. Please check again the email and password.", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ...
}
});
}
Create two child nodes from users. One for students and one for tutors.(Give both child values a value of true, otherwise firebase doesn't save the children.)
Have two registration buttons ..one for students and one for tutors. Registration for Tutor code.....
mRegistration.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(TutorsLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db= FirebaseDatabase.getInstance().getReference().child("Users").child("Tutors").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
Do the same for the students. Just change the .child("Tutors") to .child("Students") This will give you UIDs for the two different groups. And you can do the same when logging in. I think this is a better way to proceed.

How to check existed data in firebase?

I am using firebase database, but I am newbie with it. I am following this tutorial,
Now, my question is how can I check the email if it is already exist in the database? If email is already there data should not be add to db.
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView txtDetails;
private EditText inputName, inputEmail;
private Button btnSave;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying toolbar icon
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
txtDetails = (TextView) findViewById(R.id.txt_user);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
btnSave = (Button) findViewById(R.id.btn_save);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue("Realtime");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
String appTitle = dataSnapshot.getValue(String.class);
// update toolbar title
getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String name = inputName.getText().toString();
final String email = inputEmail.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email);
} else {
updateUser(name, email);
}
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Your Logic here
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
User mModel = eventSnapshot.getValue(User.class);
// Log.e("DATA" ,""+ mModel.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Update");
}
}
private void filter()
{
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
userId = mFirebaseDatabase.push().getKey();
}
User user = new User(name, email);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
/**
* User data change listener
*/
private void addUserChangeListener() {
// User data change listener
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if(!dataSnapshot.child("users").child("email").exists())
{
Log.e(TAG, "User not exists");
}
else
{
Log.e(TAG, "User exists");
}
// Check for null
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);
// Display newly updated name and email
txtDetails.setText(user.name + ", " + user.email);
// clear edit text
inputEmail.setText("");
inputName.setText("");
toggleButton();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read user", error.toException());
}
});
}
private void updateUser(String name, String email) {
// updating the user via child nodes
if (!TextUtils.isEmpty(name))
mFirebaseDatabase.child(userId).child("name").setValue(name);
if (!TextUtils.isEmpty(email))
mFirebaseDatabase.child(userId).child("email").setValue(email);
}
}
Inside ValueEventListener() check email address is exist or not
Try this
if(!dataSnapshot.child("users").child("email").exist)
then insert new value
If you are trying to create a rule for block user have 2 accounts with same email, you can use the rules inside firebase. There are rules ready for this.
Authentication -> Method -> botton functions.

Categories

Resources