Firebase: Add to Authenticated User - android

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

Related

App Stopped - Retriving data from firebase

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).

How do I save user information using Firebase with user enter unique id in android?

I am implementing an application using FireBase, in this application I have to save user information with user enter unique id. How can I do that. Actually it saving the data with random generated value. But I want to add a user enter unique id.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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 Database");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
// update toolbar title
}
#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) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email);
} else {
createUser(name, email);
}
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Save");
}
}
/**
* 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).push().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);
// 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);
}
To save user data under an unique identifier i suggest you using the email address in stead of pushing a new key or using the uid. The email address is unique and easy to use. But because Firebase does not accept . symbol in the key i suggest you encode the email address like this:
name#email.com -> name#email,com
As you see, i have changed the the dot symbol . with a coma ,. To achive this i recomand you using this methods:
static String encodeUserEmail(String userEmail) {
return userEmail.replace(".", ",");
}
static String decodeUserEmail(String userEmail) {
return userEmail.replace(",", ".");
}
Hope it helps.

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.

How to add user's display name when creating user with email and password using Firebase on Android

I am trying to add a user's display name when creating user using the createUserWithEmailAndPassword() method with Firebase on Android.
When I use the following code to update the user's profile I get an exception like so: com.google.android.gms.tasks.RuntimeExecutionException: com.google.firebase.FirebaseException: An internal error has occured. [ USER_NOT_FOUND ]
Task does not complete successfully
The displayName variable is also empty.
To code is:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
private FirebaseUser user;
private Dialog dialog;
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get FireBase FireBaseAuth instance
firebaseAuth = FirebaseAuth.getInstance();
String displayName = firebaseAuth.getCurrentUser().getDisplayName();
user = FirebaseAuth.getInstance().getCurrentUser();
TextView textView = (TextView) findViewById(R.id.txtMain);
textView.setText(displayName);
Log.i(TAG, "Display name = " + displayName);
if (user.getDisplayName() == null) {
dialog = new Dialog(this);
dialog.setContentView(R.layout.update_user_dialog);
dialog.setTitle("Update your profile...");
// set the custom dialog components - text, image and button
EditText txtName = (EditText) dialog.findViewById(R.id.txtName_user_dialog);
final String name = txtName.getText().toString().trim();
Button dialogButton = (Button) dialog.findViewById(R.id.btnUpdate_user_dialog);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Your profile has been updated.", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Profile has been updated.");
} else
Log.i(TAG, "Profile has not been updated. " + task.getResult());
}
});
}
});
dialog.show();
}
}
}
What I ultimately want to accomplish is to add a user display name when creating the user.

How to store data in realtime database in firebase during user registration?

I'm making socialmedia-like app that has user profile. I want to save their profile data upon their registration using their uid. Although the registration is successful, profile is not saving in the firebase database. I've also checked the rules, and read and write is set for authenticated users.
Here's my code:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private Button btn_reg;
private EditText etName, etEmail, etPassword, etCPassword, etMobile, etSchoolCompany, etLocation;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
btn_reg = (Button)findViewById(R.id.btnRegister);
etName = (EditText)findViewById(R.id.etName);
etEmail = (EditText)findViewById(R.id.etEmail);
etPassword = (EditText)findViewById(R.id.etPassword);
etCPassword = (EditText)findViewById(R.id.etCPassword);
etMobile = (EditText)findViewById(R.id.etMobile);
etSchoolCompany = (EditText)findViewById(R.id.etSchoolCompany);
etLocation = (EditText)findViewById(R.id.etLocation);
btn_reg.setOnClickListener(this);
}
#Override
public void onClick (View view){
if(view == btn_reg){
registerUser();
}
}
private void registerUser(){
String name = etName.getText().toString();
String mobile = etMobile.getText().toString();
String SchoolCompany = etSchoolCompany.getText().toString();
String location = etLocation.getText().toString();
final String email = etEmail.getText().toString().trim();
final String password = etPassword.getText().toString().trim();
String cpassword = etCPassword.getText().toString().trim();
progressDialog.setMessage("Registering..");
progressDialog.show();
//REGISTERING USER
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//THIS IS FOR STORING AUTHENTICATED USER'S DATA
final Firebase ref = new Firebase("https://myfirebase.firebaseio.com");
ref.authWithPassword(email, password, new Firebase.AuthResultHandler(){
#Override
public void onAuthenticated(AuthData authData){
// Authentication just completed successfully :)
Map<String, String> map = new HashMap<String, String>();
map.put("provider", authData.getProvider());
if(authData.getProviderData().containsKey("displayName")) {
map.put("displayName", authData.getProviderData().get("displayName").toString());
}
ref.child("users").child(authData.getUid()).setValue(map);
}
#Override
public void onAuthenticationError(FirebaseError error) {
//ERRORS TODO
}
});
progressDialog.hide();
Toast.makeText(RegisterActivity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(RegisterActivity.this, "Registration failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
}
}
From the createUserWithEmailAndPassword method reference
Tries to create a new user account with the given email address and password. If successful, it also signs the user in into the app.
That means you don't need to authenticate the user again after the signup process completed.
To make sure that the task is complete and the firebaseUser is not null, better add AuthStateListener to your FirebaseAuth instead of saving data inside onComplete method, the code is in the official guide
Then you can save the data if the user is authenticated.
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Map<String, String> map = new HashMap<>();
map.put("provider", user.getProviders().get(0));
if(user.getProviderData().containsKey("displayName")) {
map.put("displayName", user.getProviderData().get("displayName").toString());
}
ref.child("users").child(user.getUid()).setValue(map);
}
}
Suppose if you want to add the user name on database then write
String name = etName.getText().toString().trim();
then Simply create object of DatabaseReference class eg:
DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = myRootRef.child("User Name");
userNameRef.setValue(name);
// to add email
String email = etEmail.getText().toString().trim();
DatabaseReference userEmail = myRootRef.child("Email ");
userEmail.setValue(email);
In the same way you can do it for rest of the things
This will store the data as JSON tree where the root is myRootRef and its child will be userNameRef
For anyone else having a similar problem, a common cause of data not being persisted in Firebase is the child name in Realtime Database|Rules not matching the name in your java code:
Java code:
Again, you should be calling:
ref.child("users").child(firebaseUser.getUid()).setValue(<YOUR_POJO_OBJECT>);
instead of
ref.child("users").child(authData.getUid()).setValue(map);

Categories

Resources