Is this the best way to create a user list from facebook users to hold variables on firebase? I want each user to have a few int variables, tokens, spins, and biggestWin. but the createUser method doesn't seem to add any data to the firebase, and doesnt seem to work well with the facebook code. It always toasts "not created"
public void createUser(String mEmail, String mProvide){
Firebase rootRef = new Firebase("https://luckycashslots.firebaseio.com/data/");
Firebase userRef = rootRef.child("users");
userRef.setValue(mAuthData.getUid());
Firebase newRef = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + mAuthData.getUid() + "/");
Firebase tokRef = newRef.child("tokens");
Firebase spinRef = newRef.child("spins");
newRef.setValue(mAuthData.getProvider());
Tokens token = new Tokens("100");
Spins spin = new Spins(55);
tokRef.setValue(token);
//spinRef.setValue(spin);
rootRef.createUser(mEmail, mProvide , new Firebase.ValueResultHandler<Map<String, Object>>() {
#Override
public void onSuccess(Map<String, Object> result){
Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();
}
#Override
public void onError(FirebaseError firebaseError){
Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();
}
});
}
Creating an email+password user or authenticating a user with Facebook does indeed not store any data about that user in the Firebase Database.
If you want to store user data in the database, see the section on storing user data in the Firebase documentation.
Related
Creating an app on Android studio, have a registration page working which updates the User table on back4app - it also creates a session table with sessionID associated with the account. I'm trying to make it so once the username and password have been confirmed and added the user is brought to a new page and more details are further taken and added to the row in the same User table.
My code for the section looks like
private void addPersonalDetailsToDatabase(String firstname,
String lastname,
String dob,
String addressline1,
String addressline2,
String postcode,
String livealone,
String havecarers) {
ParseObject userList = new ParseObject("User");
userList.put("firstname", firstname);
userList.put("lastname", lastname);
userList.put("dob", dob);
userList.put("addressline1", addressline1);
userList.put("addressline2", addressline2);
userList.put("postcode", postcode);
userList.put("livealone", livealone);
userList.put("havecarers", havecarers);
userList.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(PersonalDetailsForm.this, "Successful", Toast.LENGTH_SHORT).show();
openPDConfirmed();
} else {
Toast.makeText(getApplicationContext(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
});
}
However when I run this code and enter the details it creates a new User table with a brand new row which isn't then accessed by the sessionID.
What I'm trying to do is to add these new columns and their contents to the original user table for the user that has just logged in. Is there any errors in my code or any way that I could add new columns to an already existing row.
Try ParseObject userList = new ParseObject("_User"); or ParseUser userList = new ParseUser();
Firebase real time database could not save EditText string or String test_case = "this is test case message" in setValue,but it is successfully saving databaseReference.child(id_key).setValue("given string text");
final Text_Strings text_strings = new Text_Strings(user_name, id_key, title_m, question_m);
// to save elements database referefernce called
databaseReference.child(id_key).setValue(text_strings, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Data could not be saved ", databaseError.getMessage());
} else {
// it is always saying data
Toast.makeText(getContext(), "Data saved succcessfully ", Toast.LENGTH_SHORT).show();
}
}
});
// to save id_key for test cases
databaseReference.child(id_key).setValue(test_case);
/// to save string elements for test cases
databaseReference.child(id_key).setValue("given string text");
}
});
// return view
return view;
}
}
;
Check whether you are in test mode or applied read write rules correctly .
You can refer to Docs for Read and Write data in Firebase Realtime Database : https://firebase.google.com/docs/database/android/read-and-write
Please paste you complete activity code to better understand your problem.
I have an app in which a user has 2 options, Sign in and Sign up.
In the sign in option, the user enters his firebase username and password and goes to the MainActivity successfully.
In the Signup option, the user sees 4 screens simultaneously in which he/she is asked to enter some data about themselves. In the last screen, the user is asked for his email/username for firebase registration but for some reason, it gives an error when entering the data into firebase DB. And the most annoying thing is that android studio isn't even showing me the error.
Anyhow, the code is below. I have marked as a comment, "I think the main problem arises here." as a comment in my code. The flow is like this, it comes from RegScreen1 -> RegScreen2 -> RegScreen3 -> RegScreen4 -> MainActivity. But, for some reason, after RegScreen4 -> RegScreen3 appears.
Bundle b = getIntent().getExtras();
final String name = b.getString("name");
final String dob = b.getString("dob");
final String gender = b.getString("gender");
final String age = b.getString("age");
final String smoke = b.getString("smoke");
final String type = b.getString("type");
final String today = b.getString("today");
final String email = emailEditTextRegScreenFour.getText().toString();
final String password = passwordEditTextRegScreenFour.getText().toString();
if (email.contains("#") && email.contains(".com"))
{
Toast.makeText(RegistrationScreenFour.this, "# and com available", Toast.LENGTH_SHORT).show();
Toast.makeText(RegistrationScreenFour.this, "email: " + email + "\npassword: " + password, Toast.LENGTH_SHORT).show();
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegistrationScreenFour.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PersonContract.Person.COL_SMOKER_NAME, name);
values.put(PersonContract.Person.COL_SMOKER_DOB, dob);
values.put(PersonContract.Person.COL_SMOKER_GENDER, gender);
values.put(PersonContract.Person.COL_SMOKER_AGE_STARTED_SMOKING, age);
values.put(PersonContract.Person.COL_SMOKER_SMOKES_IN_ONE_DAY, smoke);
values.put(PersonContract.Person.COL_SMOKER_SMOKE_ANY_TODAY, today);
values.put(PersonContract.Person.COL_SMOKER_USERNAME, email);
values.put(PersonContract.Person.COL_SMOKER_PASSWORD, password);
values.put(PersonContract.Person.COL_SMOKER_LAST_LOGIN, true);
//dbHelper.addSmokerEntry(values);
PersonDetails personDetails =
new PersonDetails(name, Integer.parseInt(age),
dob, gender, smoke, today, email, password, type);
// I think the main problem arises here.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
DatabaseReference courseRef = database.getReference("PersonDetails");
courseRef.child(email).setValue(personDetails);
Toast.makeText(RegistrationScreenFour.this, "task successful", Toast.LENGTH_SHORT).show();
Intent i = new Intent(RegistrationScreenFour.this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
I found one more mistake
You have to initialize Your firebase database object like this.
"PersonDetails" will be a child of Your database.
DatabaseReference courseRef = FirebaseDatabase.getInstance().getReference().child("PersonDetails");
courseRef.child(email).setValue(personDetails);
I face the same problem.
After creating User with E-mail and Password when You are storing data to Fire-base database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference courseRef = database.getReference().child("PersonDetails");
courseRef.child(email).setValue(personDetails);
At this point problem is Your are setting a User's E-mail as Child.
But Fire-base does not allow this.
"#" and "." are invalid characters here
You can go to Fire-base console and check by manually adding data if You set an E-mail as Key fire-base will not allow it.
So You have to do some additional work with the email
In my case I managed it by removing the "#" and "." from the email.
id = email.replace("#", "-");
id = id.replace(".", "-");
courseRef.child(id).setValue(personDetails);
I am using Firebase for both authentication and realtime database. My authentication code was successfully run also my enter value to database code also run, but when I am coding for fetch value in database, I am getting run time error trying to enter value at Firebase database:
FATAL EXCEPTION: main
Process:com.xxx.xxx, PID: 22601
com.google.firebase.database.DatabaseException: Invalid Firebase Database
path: https://xxx-exxe.firebaseio.com/. Firebase Database paths must not contain '.', '#', '$', '[', or ']'
My Code is :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference("https://korsa-e03ae.firebaseio.com/");
reference.addValueEventListener(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
Offerride user = dataSnapshot.getValue(Offerride.class);
if (user == null){
Toast.makeText(getContext(),"User data is null!",Toast.LENGTH_LONG).show();
return;
}
tvsource.setText(user.source + " , " + user.destination + " , " + user.startDate + " , " + user.startTime);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getContext(), "Failefddd", Toast.LENGTH_LONG).show();
}
});
I think the answer is quite obvious you don't need to specific the url because app is already link to the database when you set up the project
just change from
DatabaseReference reference = database.getReference("https://korsae03ae.firebaseio.com/");
to
DatabaseReference reference = database.getReference();
Then it should work
Url of your database is in your google-services.json file.
By firebase docs https://firebase.google.com/docs/database/admin/retrieve-data to read data, you can do the following:
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
Instead of using getReferance use, getReferanceFromUrl.
and in your case: database.getReference.child("posts");
Is there a way to retrieve data from a specific user who is authenticated via firebase through ID?
For example to retrieve information like name, photo etc.
Thanks in advance.
This is more of a port of the iOS answer i have given here
Firebase provides authentication for users using the FIRAuth Clases/API
However they can't be edited with custom fields like the Firebase Database.
To allow custom fields for user, you need to duplicate users in the Database with the same unique uid you receive in the auth of the user. Something like this
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
String name = user.displayName;
String email = user.email;
String photoUrl = user.photoURL;
String uid = user.uid;
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = database.getReference("users").push().getKey();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put( "uid", uid);
childUpdates.put( "name", name);
// other properties here
database.getReference("users").updateChildren(childUpdates, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
}
}
});
}
We push it at the users end point in our db and with the uid key by the following line /users/\(key).
Now you can retrieve users detail from your database by querying anywhere in your code.