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);
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();
I am new to firebase so, please bear with me. I am making a registration using firebase realtime database in android studio. What I want to do is that when the user enters her firstname and lastname, the system will set the username for them by taking the first character of the firstname and concatenate it with the lastname.
Example:
Name: John Smith
Username: jsmith
There are cases that there would be a duplication for the username because there are so many names that starts with J with the lastname Smith. So what I want is to add an integer if the username already exist.
jsmith, jsmith1, jsmith2, etc...
I know I needed to add a loop but I just don't know how to construct it. Here is my code:
public void insertAccount(){
acctstatus.setText("Active");
accttype.setText("Employee");
final String status = acctstatus.getText().toString();
final String type = accttype.getText().toString();
final String lname = empLname.getText().toString();
final String fname = empFname.getText().toString();
final String newfname = fname.substring(0,1).toLowerCase();
final String newuname = newfname+lname.toLowerCase();
// empuname.setText(newuname);
// final String uname = empuname.getText().toString();
// String passw = UUID.randomUUID().toString().substring(0,5);
// emppassw.setText(passw);
// String newpassw = emppassw.getText().toString();
String newpassw = newuname;
//
final int num = 0;
accountFirebaseReference.orderByChild("acct_uname").equalTo(newuname)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String username = newuname+num+1;
empuname.setText(username);
final String acctuname = empuname.getText().toString();
Toast.makeText(getApplicationContext(), "Username: "+acctuname, Toast.LENGTH_LONG).show();
}else{
String username = newuname;
empuname.setText(username);
Toast.makeText(getApplicationContext(), "Username: "+empuname, Toast.LENGTH_LONG).show();
}
}
final String acctuname = empuname.getText().toString();
final String acctpassw = empuname.getText().toString();
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//addAccount(newuname, newpassw, type, status);
}
merely a suggestion. If a username exists, add a 01, like this jDoe01,jDoe02.... then jDoe011, etc.
Then, if a document exists, get the index of that zero, (it will always exist)
you can use something like int index = yourUserNameFromFirebase.indexOf('0');
then, you can use that index to get the number from the document, through doing a substring:
String numberValue = yourUserNameFromFirebase.substring(index);
int countOfDuplicateNames = Integer.valueOf(numberValue);
then, you can simply increment countOfDuplicateNames and make a new user, just remember to always ensure that the 0 is there, as this is the only way to get a reference to the number.
to pseudo code it, your new username will be something like this:
initial + surname + '0' + countOfDuplicateNames+1
Note
Sorry this answer does not cater for starting at an index of 1 :D
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.
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.
I've been working with Xamarin for a few weeks now and i'm trying to find the best practices for using SQLite ORM queries.I have a log in page which is launched first before users can access the app.I have the database created before this first activity comes to the screen and administrator log in details inserted into the user's table as soon as the tables are created.The point is,the admin is meant to log in and import an xml file containing all of the other user's personal information.This information is read from the file and saved to sqlite as well.
Next,the other users can log in after their details have been imported and saved successfully.My challenge is,at the point of logging in,i would like to verify the details as follows:
1.Compare the entered username with a single username from the db
**2.Check the password entered to see if it matches the username entered **
I'm currently using a select query to pull up all the passwords from the database,before comparing the two strings(from the db and from the edit text field).If it's a large db however,reading all the data will be quite expensive.How do i go about this?
How do i also look up the password for that username?
Below is my code:
namespace sample.NameSpace
{
[Activity (MainLauncher = true)]
public class MainActivity : Activity
{
Button login = FindViewById<Button> (Resource.Id.login);
try{
login.Click += (object sender, EventArgs e) => {
if (TextUtils.IsEmpty(userName.Text.ToString())) {
makeToast();
} else if (TextUtils.IsEmpty(password.Text.ToString())) {
makeToast();
} else {
returningUser = userName.Text.ToString().Trim();
returningUserPassword = password.Text.ToString().Trim();
}
//Check to see if the name is in the db already
List<string> allUsers = GetAllUserNames();
//Loop through the list of names and compare the retrieved username with the name entered in the text field
string retrievedDbName ="";
foreach(string name in allUsers )
{
retrievedDbName = name .Trim();
}
//Verify name
if(retrievedDbName .Equals(returningUser))
{
Toast.MakeText(this,
"Login Successful !", ToastLength.Short).Show();
Intent intent = new Intent (this, typeof(HomeActivity));
StartActivity (intent);
}
else
{
Toast.MakeText(this, "User Name or Password does not match", ToastLength.Short).Show();
}
};
} catch(Exception e){
logger.Exception (this, e);
}
public List<string>GetAllUserNames()
{
List<UserInfoTable> allUserNames = new List<UserInfoTable> ();
allUserNames = dataManager.GetSingleUserName ();
string name = "";
foreach(var UserName in allUserNames)
{
Console.WriteLine ("Usernames from db :" + name.ToString());
}
return allUserNames;
}
Then the DataManager class:
public List<UserInfoTable> GetSingleUserName()
{
UserInfoTable user = new UserInfoTable ();
using (var db = dbHandler.getUserDatabaseConnection ()) {
var userName = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ?", user.USER_NAME);
return userName;
}
}
public bool CheckLogin(string user, string password)
{
bool valid = false;
using (var db = dbHandler.getUserDatabaseConnection ()) {
var user = db.Query<UserInfoTable> ("select * from UserInfoTable where user_name = ? and password = ?", user, password);
if (user != null) valid = true;
}
return valid;
}