Creating link between Firebase real-time database and authenticated users - java

So far I have successfully implemented Firebase within my Android application, where I can add users to the Authentication portal through a SignUpActivity, and also add maintenance issues to the real-time database through a MaintenanceActivity.
However, at present, none of the database data is linked to specific users, which is what I want to achieve. So essentially at the moment when I log in as an arbitrary user, the same data will always come up.
Presumably, and having read several other threads on this, the User UID will be required here and will need to be present for every maintenance record.
I'm not sure, however, how I can implement this. Possibly a layer of authentication needs implemented into the MainActivity?
Finding it hard to get my head around this, so any help on this would be much appreciated.
SignUpActivity
mDatabase = FirebaseDatabase.getInstance().getReference().child("users");
final DatabaseReference[] ref = new DatabaseReference[1];
final FirebaseUser[] mCurrentUser = new FirebaseUser[1];
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser[0] = task.getResult().getUser();
ref[0] =mDatabase.child(mCurrentUser[0].getUid());
ref[0].child("email").setValue(email);
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
});

You can implement it like this:
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
DatabaseReference ref;
FirebaseUser mCurrentUser;
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignUpActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toasty.info(getApplicationContext(), "creation of account was: " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
mCurrentUser= task.getResult().getUser();
ref=mDatabase.child(mCurrentUser.getUid());
ref.child("email").setValue(email);
ref.child("name").setValue(name);
}
});
You can implement it like the above, then in your db you will have:
Users
userid
name: userx
email: userx#gmail.com
After you authenticate the user using createUserWithEmailAndPassword(email, password), you can then retrieve the email and name, and whatever extra data was written and send it to the database.
This mCurrentUser.getUid() will give you the userid, that you can use in the database.

After adding your project to the firebase
U can also try this.
public class RegisterActivity extends AppCompatActivity implements
View.OnClickListener {
private static final String TAG = "MAGIC";
Firebase mref =null;
private User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Firebase.setAndroidContext(this);
mAuth = FirebaseAuth.getInstance();
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_new_email);
password = (EditText) findViewById(R.id.edit_text_new_password);
}
#Override
public void onStop() {
super.onStop();
}
//This method sets up a new User by fetching the user entered details.
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString().trim());
user.setPassword(password.getText().toString().trim());
}
#Override
public void onClick(View v) {
//paste your firebase database link address here.
mref = new Firebase("https://citypride-97902.firebaseio.com/");
createNewAccount(email.getText().toString(),
password.getText().toString());
}
private void createNewAccount(String email, String password) {
Log.d(TAG, "createNewAccount:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "Register Successfully " + task.isSuccessful());
hideProgressDialog();
if (!task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "Registration failed.",
Toast.LENGTH_SHORT).show();
hideProgressDialog();
} else {
onAuthenticationSuccess(task.getResult().getUser());
Toast.makeText(RegisterActivity.this, "Register Successful.",
Toast.LENGTH_SHORT).show();
} hideProgressDialog();
}
});
}
private void onAuthenticationSuccess(FirebaseUser mUser) {
// Write new user
saveNewUser(mUser.getUid(), user.getEmail(), user.getPassword());
signOut();
// Go to LoginActivity
Intent i =new Intent(LoginActivity.this, YourActivity.class);
startActivity(i);
}
private void saveNewUser(String userId,
String email, String password) {
User user = new User(userId,email,password);
mref.child("Users").child(name).setValue(user);
}
private void signOut() {
mAuth.signOut();
}
//This method, validates email address and password
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
if(!Patterns.EMAIL_ADDRESS.matcher(userEmail).matches()){
Toast.makeText(getApplicationContext(),"please enter valid
email",Toast.LENGTH_LONG).show();
}
if (userEmail.isEmpty() && userPassword.isEmpty()){
Toast.makeText(getApplicationContext(),"all fields are
mandatory",Toast.LENGTH_LONG).show();
}
return valid;
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading");
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
Below is User class
class User {
private String id;
private String email;
private String password;
public User() {
}
public User(String id,String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
this will show email and password field in your firebase database.

Related

Firebase Realtime Database not getting updated // Data not getting added to the Firebase Realtime Database

so I'm making a chatting app, I'm facing the problem where I'm trying to add the user details to my Realtime database, and it's just not working so I can later on show them to the logged in user
this is my Register Activity
public class RegisterActivity extends AppCompatActivity {
EditText username;
EditText email;
EditText password;
Button registerButton;
TextView oldMember;
FirebaseAuth auth;
DatabaseReference myRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
username = findViewById(R.id.usernameEditText);
email = findViewById(R.id.emailEditText);
password = findViewById(R.id.passwordEditText);
registerButton = findViewById(R.id.RegisterButton);
oldMember = findViewById(R.id.LoginTextView);
auth = FirebaseAuth.getInstance();
myRef = FirebaseDatabase.getInstance().getReference("MyUsers");
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String usernameText = username.getText().toString();
String emailText = email.getText().toString();
String passwordText = password.getText().toString();
if(TextUtils.isEmpty(usernameText) || TextUtils.isEmpty(emailText) || TextUtils.isEmpty(passwordText)){
Toast.makeText(RegisterActivity.this, "Please Fill the Required Info", Toast.LENGTH_SHORT).show();
} else {
Register(usernameText, emailText, passwordText);
}
}
});
oldMember.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
});
}
private void Register(String username, String email, String password){
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull #org.jetbrains.annotations.NotNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser firebaseUser = auth.getCurrentUser();
String userid = firebaseUser.getUid();
myRef = FirebaseDatabase.getInstance()
.getReference("MyUsers")
.child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
myRef.setValue(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull #NotNull Task<Void> task) {
if(task.isSuccessful()){
Intent intent = new Intent(getApplicationContext(), MainHomeActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
});
} else {
Toast.makeText(RegisterActivity.this, "Invalid Email or Password", Toast.LENGTH_SHORT).show();
}
}
});
}
}
this is how my realtime database looks like
and these are my realtime database rules
"rules": {
".read": true,
".write": true
}
}
I would appreciate any help!
Instead of using HashMap for adding data to firebase realtime database
myRef = FirebaseDatabase.getInstance()
.getReference("MyUsers")
.child(userid);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", userid);
hashMap.put("username", username);
hashMap.put("imageURL", "default");
Create a model class for the information
Example model class for the given information
public class userRegisteration(){
Sting id;
String username;
String imageURL;
//to add details it needs an empty constructor
userRegisteration(){}
userRegisteration(String id,String username,String imageURL){
this.id = id;
this.username = username;
this.imageURL = imageURL;
}
public void setID(String id){this.id = id}
public void setUsername(String username){this.username= username}
public void setImgeURL(String imageURL){this.imageURL = imageURL}
public String getID(){return id}
public String getUsername(){return username}
public String getImageURL(){return imageURL}
}
Trust me it'll work

authentication problem in fire base using android studio

I am working on a project which required firebase utilities so I did all those things required but my authentication is not taking place and thereby my data is not being uploaded in the firestore. I have tried many things and found that during the time of execution my onComplete listener is calling failure and thus a toast is popped authentication failure so I think the main problem lies in the onComplete listener but I couldn't fix it. My code is as follows-
*
private TextView username;
private TextView password;
private AutoCompleteTextView email;
private ProgressBar progress_bar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username_account);
password = findViewById(R.id.password_account);
email = findViewById(R.id.email_account);
Button create_account = findViewById(R.id.create_acct_button);
progress_bar = findViewById(R.id.create_acct_progress);
firebaseAuth = FirebaseAuth.getInstance();
create_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(email.getText().toString())
&& !TextUtils.isEmpty(password.getText().toString())
&& !TextUtils.isEmpty(username.getText().toString())) {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
String Username = username.getText().toString().trim();
createUserEmailAccount(Email, Password, Username);
} else {
Toast.makeText(CreateAccountActivity.this,
"Empty Fields Not Allowed",
Toast.LENGTH_LONG)
.show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
progress_bar.setVisibility((View.VISIBLE));
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( CreateAccountActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete( #NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Map<String, Object> userobj = new HashMap<>();
userobj.put("userId", "currentuserId");
userobj.put("username", username);
db.collection("journal")
.add(userobj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot successfully written!");
progress_bar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(CreateAccountActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progress_bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
}*

Android - How to show created user in Firestore

i'm trying to show the created user/user info in my firestore database but i cant seem to get it. I have a Question model already created that will show up whenever a new question is submitted however when I try to create a user, the information doesnt show in the Database.
Ideally, of course, i'd like to have the info in the database. i'd also like to show that the question was created by an author.
Any and all help is appreciated. Ive been following a series of tutorials trying to blend them all to make my code work but im struggling on this part.
here is my relative code so far:
SignUpActivity.java
private void registerUser() {
final String email = editTextEmail.getText().toString().trim();
final String userName = editTextUserName.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final List<Question> questionsList = new ArrayList<>();
final String firstName = "default firstName";
final String lastName = "default lastName";
CollectionReference usersRef = FirebaseFirestore.getInstance().collection("Users");
User userInfo = new User(userName, firstName, lastName, email, questionsList);
// DocumentReference docPath = FirebaseFirestore.getInstance().document(mAuth.getCurrentUser()).
userInfo.setUserName(userName);
usersRef.add(userInfo);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
CollectionReference usersRef = FirebaseFirestore.getInstance().collection("Users");
usersRef.add(new User(userName, firstName, lastName, email, questionsList));
FirebaseUser user = mAuth.getCurrentUser();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(userName).build();
user.updateProfile(profileChangeRequest);
}
}
};
mAuth.addAuthStateListener(mAuthListener); // need this to change info on Firebase Firestore
String usernameTest = user.getDisplayName();
Toast.makeText(SignUpActivity.this, "info saved hopefully", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(SignUpActivity.this, DashboardActivity.class));
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
}
});
}
NewQuestionActivity.java
private void saveQuestion(){
String questionString = questionEditText.getText().toString();
String questionAnswerString = answerEditText.getText().toString();
String authorFirebase = FirebaseAuth.getInstance().getCurrentUser().toString(); //TODO: HOW TO SET THIS Author
authorTextView.setText(authorFirebase);
int priority = numberPickerPriority.getValue();
String tagInput = editTextTags.getText().toString();
String[] tagArray = tagInput.split("\\s*, \\s*");
List<String> tags = Arrays.asList(tagArray);
if (questionString.trim().isEmpty() || questionAnswerString.trim().isEmpty()) {
Toast.makeText(this, "Please insert a question and a proposed answer", Toast.LENGTH_SHORT).show();
return;
}
CollectionReference questionRef = FirebaseFirestore.getInstance().collection("Questions");
questionRef.add(new Question(questionString, questionAnswerString, priority, tags, authorFirebase));
Toast.makeText(this, "Question Added", Toast.LENGTH_SHORT).show();
finish();
}
usermodel
package com.example.stairmaster.models;
import java.util.List;
import androidx.databinding.BaseObservable;
import com.google.firebase.firestore.Exclude;
public class User extends BaseObservable {
#Exclude
private int id;
private String firstName;
private String lastName;
private String userName;
private String email;
private List<Question> questions;
public User() {
// no arg constructor needed
}
public User(String firstName, String lastName, String userName, String email, List<Question> questions) {
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.email = email;
this.questions = questions;
}
public int getId() {
return id;
}
public String getUserName(String userName) { return userName;}
public void setUserName(String userName) { this.userName = userName; }
public String getFirstName(String firstName) {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName(String lastName) {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail(String email) {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Question> getQuestions() {
return questions;
}
}
Issue is firstname, and lastname are not being created in the database as they should be. ID is incorrect (i'm still not too sure what to assign as an ID to users so that they unique), and the questions list is another thing i still need to figure out.
Finally got it working. although the only thing i cant seem to get working is storing the userId when its created so i have to do that later somewhere.
Code under registerUser looks like this now:
final CollectionReference usersColRef = FirebaseFirestore.getInstance().collection("Users");
final User userInfo = new User(firstName, lastName, userName, userEmail, mAuthUserId);
final DocumentReference userDocRef = usersColRef.document(userEmail);
userDocRef.set(userInfo).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
mAuthUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
userDocRef.update(
"firstname", firstName,
"lastname", lastName,
"userEmail", userEmail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: userinfo was created");
}
});
Log.d(TAG, "onSuccess: user was created");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: failed to create user in signup" + e);
}
});

Why am I getting a Null Pointer Exception when reading user data from Firebase?

I'm currently creating an android application that allows people to register and login to an account, add details to their profile and then display those details on another page.
I've successfully managed to log users into my application and store their profile data, however, I get a null pointer exception on line 90 in the class ViewProfileActivity. Which is: uInfo.setAddress(ds.child(userID).getValue(UserDetails.class).getAddress());
I've made sure that the database is read and write enabled. Any help would be greatly appreciated.
Below is all possible relevant code and an image of the firebase database structure
ViewProfileActivity
public class ViewProfileActivity extends AppCompatActivity {
private static final String TAG = "ViewDatabase";
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
private ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
mListView = (ListView) findViewById(R.id.listview);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
toastMessage("Successfully signed in with: " + user.getEmail());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
toastMessage("Successfully signed out.");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UserDetails uInfo = new UserDetails();
uInfo.setAddress(ds.child(userID).getValue(UserDetails.class).getAddress()); //set the email
uInfo.setDateOfBirth(ds.child(userID).getValue(UserDetails.class).getDateOfBirth());
uInfo.setName(ds.child(userID).getValue(UserDetails.class).getName()); //set the name
uInfo.setPhoneNumber(ds.child(userID).getValue(UserDetails.class).getPhoneNumber());
//display all the information
Log.d(TAG, "showData: name: " + uInfo.getName());
Log.d(TAG, "showData: email: " + uInfo.getAddress());
Log.d(TAG, "showData: phone_num: " + uInfo.getPhoneNumber());
Log.d(TAG, "showData: phone_num: " + uInfo.getDateOfBirth());
ArrayList<String> array = new ArrayList<>();
array.add(uInfo.getName());
array.add(uInfo.getAddress());
array.add(uInfo.getPhoneNumber());
array.add(uInfo.getDateOfBirth());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
mListView.setAdapter(adapter);
}
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
CreateProfileActivity
public class CreateProfileActivity extends AppCompatActivity {
private FirebaseAuth auth;
private TextView textViewUserEmail;
private EditText editTextName;
private EditText editTextPhoneNumber;
private EditText editTextPostalAddress;
private EditText editTextDateOfBirth;
private Button buttonSaveProfile;
private Button buttonLogout;
private DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_profile);
auth = FirebaseAuth.getInstance();
if(auth.getCurrentUser() == null)
{
finish();
startActivity(new Intent(this,LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
FirebaseUser user = auth.getCurrentUser();
textViewUserEmail = (TextView) findViewById(R.id.textViewUserEmail);
textViewUserEmail.setText("Welcome " + user.getEmail());
buttonLogout = (Button) findViewById(R.id.buttonLogout);
buttonSaveProfile = (Button) findViewById(R.id.buttonSaveProfile);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
editTextPostalAddress = (EditText) findViewById(R.id.editTextPostalAddress);
editTextDateOfBirth = (EditText) findViewById(R.id.editTextDateOfBirth);
buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.signOut();
finish();
startActivity(new Intent(CreateProfileActivity.this, LoginActivity.class));
}
});
buttonSaveProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveUserInformation();
}
});
}
private void saveUserInformation()
{
String address = editTextPostalAddress.getText().toString().trim();
String dateOfBirth = editTextDateOfBirth.getText().toString().trim();
String name = editTextName.getText().toString().trim();
String phoneNumber = editTextPhoneNumber.getText().toString().trim();
UserInformation userInformation = new UserInformation(name, address, dateOfBirth, phoneNumber);
FirebaseUser user = auth.getCurrentUser();
databaseReference.child("users").child(user.getUid()).setValue(userInformation);
Toast.makeText(this, "Information Saved...", Toast.LENGTH_SHORT).show();
startActivity(new Intent(CreateProfileActivity.this, ViewProfileActivity.class));
}
}
UserDetails Class
public class UserDetails
{
public String name;
public String address;
public String dateOfBirth;
public String phoneNumber;
public UserDetails()
{
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
I guess that you are not referring to the data that you want
instead of this
myRef = mFirebaseDatabase.getReference();
use this to point to your data
myRef = mFirebaseDatabase.getReference().child("users");
change this line
myRef.addValueEventListener(new ValueEventListener()...
with this
myRef.child("users").addValueEventListener(new ValueEventListener()...
also in your UserDetails.class press in one of the variables Fn + alt + insert , select Constructor and select all your variables and make a constructor for them , and do not delete the empty one keep it there too.

How to prevent same user logging in from different devices ? My app is paid , so I dont want credentials to be shared

I am new to firebase , but I managed to develop an app using firebase
-email&password authentication
This app is for an organization's members so there is no sign up on the app , the organization gives me a list which I add to user list.My problem here is , I have only 45 registered users ,but there are almost 85 who are using the app.I understand I should be using an auth token , but I am not quite clear.Can anybody explain the easiest way I could prevent multiple logins simultaneously ?
I have attached the login code ( I tried storing device names , but was a bad way )so can anybody please help me out on what has to be done?
public class EmailLogin extends AppCompatActivity implements
View.OnClickListener {
public String Email;
private static final String TAG = "EmailPassword";
public static int device = 0;
private TextView forgoPwd;
private TextView mDetailTextView;
private EditText mEmailField;
private EditText mPasswordField;
private ProgressDialog PD;
private CheckBox saveLoginCheckBox;
private SharedPreferences loginPreferences;
private SharedPreferences.Editor loginPrefsEditor;
private Boolean saveLogin;
// [START declare_auth]
private FirebaseAuth mAuth;
// [END declare_auth]
private DatabaseReference root;
// [START declare_auth_listener]
private FirebaseAuth.AuthStateListener mAuthListener;
// [END declare_auth_listener]
private String temp_key;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.emailpass);
PD = new ProgressDialog(this);
PD.setMessage("Loading...");
PD.setCancelable(true);
PD.setCanceledOnTouchOutside(false);
// Views
mEmailField = (EditText) findViewById(R.id.field_email);
Email = mEmailField.toString();
mPasswordField = (EditText) findViewById(R.id.field_password);
Button btnCount = (Button) findViewById(R.id.email_sign_in_button);
// Button regis = (Button) findViewById(R.id.regis);
saveLoginCheckBox = (CheckBox)findViewById(R.id.checkBox);
loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin == true) {
mEmailField.setText(loginPreferences.getString("username", ""));
mPasswordField.setText(loginPreferences.getString("password", ""));
saveLoginCheckBox.setChecked(true);
}
//regis.setOnClickListener(this);
forgoPwd = (TextView)findViewById(R.id.forgo);
forgoPwd.setOnClickListener(this);
// Buttons
btnCount.setOnClickListener(this);
// findViewById(R.id.email_create_account_button).setOnClickListener(this);
// findViewById(R.id.sign_out_button).setOnClickListener(this);
// [START initialize_auth]
mAuth = FirebaseAuth.getInstance();
// [END initialize_auth]
// [START auth_state_listener]
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// [START_EXCLUDE]
updateUI(user);
// [END_EXCLUDE]
}
};
// [END auth_state_listener]
}
public ProgressDialog mProgressDialog;
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
// [START on_start_add_listener]
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
// [END on_start_add_listener]
// [START on_stop_remove_listener]
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
// [END on_stop_remove_listener]
private void createAccount(String email, String password) {
Log.d(TAG, "createAccount:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
// [START create_user_with_email]
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// 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(EmailLogin.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
hideProgressDialog();
// [END_EXCLUDE]
}
});
// [END create_user_with_email]
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (saveLoginCheckBox.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", mEmailField.getText().toString());
loginPrefsEditor.putString("password", password);
loginPrefsEditor.commit();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
if (!validateForm()) {
return;
}
PD.show();
showProgressDialog();
// [START sign_in_with_email]
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
if (task.isSuccessful())
{
onAuthSuccess(task.getResult().getUser());
}
// 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()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(EmailLogin.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
// [START_EXCLUDE]
if (!task.isSuccessful()) {
// mStatusTextView.setText(R.string.auth_failed);
}PD.dismiss();
hideProgressDialog();
// [END_EXCLUDE]
}
});
// [END sign_in_with_email]
}
private void onAuthSuccess(FirebaseUser user) {
if (device == 0)
getDeviceName();
device++;
String username = usernameFromEmail(user.getEmail());
Intent intent = new Intent(getApplicationContext(),Home_screen.class);
intent.putExtra("user",username);
startActivity(intent);
finish();
}
public String getDeviceName() {
String manufacturer = Build.MANUFACTURER;
String model = Build.MODEL;
root = FirebaseDatabase.getInstance().getReference().child("users");
doDb(manufacturer);
return manufacturer+model ;
}
private void doDb(String manu) {
Map<String,Object> map = new HashMap<String, Object>();
temp_key = root.push().getKey();
root.updateChildren(map);
DatabaseReference mess_root = root.child(temp_key);
Map<String,Object> map2 = new HashMap<String, Object>();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
int index = email.indexOf('#');
email = email.substring(0,index);
map2.put("user",email);
map2.put("msg",manu);
mess_root.updateChildren(map2);
}
private String usernameFromEmail(String email) {
if (email.contains("#")) {
return email.split("#")[0];
} else {
return email;
}
}
private void signOut() {
mAuth.signOut();
updateUI(null);
}
private boolean validateForm() {
boolean valid = true;
String email = mEmailField.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmailField.setError("Required.");
valid = false;
} else {
mEmailField.setError(null);
}
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(password)) {
mPasswordField.setError("Required.");
valid = false;
} else {
mPasswordField.setError(null);
}
return valid;
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
//Timer timer = new Timer();
//timer.schedule(new TimerTask(){
// public void run() {
Intent i = new Intent(EmailLogin.this, Home_screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
// return;
// }
// }, 600000);
}
/*
if (user != null) {
Intent intent = new Intent(getApplicationContext(),Home_screen.class);
startActivity(intent);
finish();
mStatusTextView.setText(getString(R.string.emailpassword_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
findViewById(R.id.email_password_buttons).setVisibility(View.GONE);
findViewById(R.id.email_password_fields).setVisibility(View.GONE);
} */
else {
// mStatusTextView.setText(R.string.signed_out);
// mDetailTextView.setText(null);
// findViewById(R.id.email_password_buttons).setVisibility(View.VISIBLE);
// findViewById(R.id.email_password_fields).setVisibility(View.VISIBLE);
}
}
#Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.email_sign_in_button) {
signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
}
//if(i == R.id.regis)
{
}
if(i == R.id.forgo) {
FirebaseAuth auth = FirebaseAuth.getInstance();
String mail = mEmailField.getText().toString();
if (TextUtils.isEmpty(mail)) {
mEmailField.setError("Required.");
} else {
auth.sendPasswordResetEmail(mEmailField.getText().toString())
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(EmailLogin.this, "Email sent to your account",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
}
You can employ a session manager, which just keeps track of the last session and terminates all other sessions for that user.
Generate a UUID on the client every time the app launches (lets call it sessionId). If the user is signed in, or when the user signs in, write that sessionId to the user's document in the remote database (lets call this field lastSessionId).
Listen for changes to this document for the currently-signed-in user and make note when lastSessionId changes.
When another client launches the app with the same auth credentials, that client is also given a random sessionId and that sessionId is also written to the database, to the same document, overwriting lastSessionId. All of the clients signed in with these credentials (including this client) see the change in lastSessionId and for every client where the local sessionId (that was generated on the client) does not equal the new lastSessionId, that client is automatically signed out, thus only allowing one client to be signed in at a time for each credential.
I understand I should be using an auth token
That won't work. Whenever a user signs in on a device, they get a new auth token. So the same user being signed in on two devices, will have to different auth tokens.
But they will have the same UID. So I'd actually store the uid and something that identifies the active device in the database.
activeDeviceByUser
<uid>: <device ID>
Then remove that when the user signs out or disconnects.

Categories

Resources