I am using cloud Firestore as database, when I am clicking on login button, it is not updating the value at first but on second click it updates.
When I click on Login, at first it takes empty values, but on second click it takes the value entered. Same happens when I change text and press login again, it takes previous values and on second click it takes updated values.
public class LoginActivity extends AppCompatActivity {
private TextView appName;
private TextInputEditText registrationNumber;
private TextInputEditText password;
private User userSent;
private FirebaseFirestore db;
private CollectionReference collectionReference;
String result="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
db = FirebaseFirestore.getInstance();
db.enableNetwork();
collectionReference = db.collection("/user");
registrationNumber = findViewById(R.id.regno);
password = findViewById(R.id.password);
userSent = new User();
appName = findViewById(R.id.appname);
AssetManager assetManager = getApplicationContext().getAssets();
Typeface typeface = Typeface.createFromAsset(assetManager,"fonts/Ubuntu-Regular.ttf");
appName.setTypeface(typeface);
}
public void onLogin(View view){
userSent.setRegistrationNumber(registrationNumber.getText().toString());
userSent.setPassword(password.getText().toString());
if(!userSent.getRegistrationNumber().isEmpty() && !userSent.getPassword().isEmpty()) {
authenticateUser(userSent);
}
else{
Toast.makeText(this, "Registration Number or Password cannot be empty", Toast.LENGTH_LONG).show();
}
//Login Result
Log.d("Login Result: " , result);
if(result.contains("success")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
else if(result.length()>0){
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
}
public void authenticateUser(final User sUser){
final String registration_number = sUser.getRegistrationNumber();
final String password = sUser.getPassword();
collectionReference.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
Map<String, Object> map;
map = queryDocumentSnapshot.getData();
String reg_no = (String) map.get("registration_number");
String pass = (String)map.get("password");
if(registration_number.equals(reg_no) && password.equals(pass)){
result = "success";
return;
}
else if(registration_number.equals(reg_no)){
result = "Incorrect Password";
return;
}
else{
result = "User does not exist";
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
result = "Error Connecting to Server";
}
});
}
}
Related
When i try to go to the next activity by pressing the sign_up in the sign up page or log in in the log page when the user already exists, the app just exits and brings up an error.
Sign up Activity
// variable
final String TAG ="signUp";
private MaterialEditText edit_name;
private MaterialEditText edit_password;
//DECLARING & INITIALISING BUTTON TO SIGN UP
FButton sign_Up;
final String KEY_NAME = "name";
final String KEY_PASSWORD ="password";
final String KEY_MARKS ="marks";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private DocumentReference user_reference = db.document("Users/Users details");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up);
//INITIALISING THE EDITTEXT VIEWS
edit_name = findViewById(R.id.editName);
edit_password = findViewById(R.id.editPassword);
sign_Up = findViewById(R.id.btn_signUp);
sign_Up.setOnClickListener(view ->
{
user_reference.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>()
{
Map<String, Object> users = new HashMap<>();
String name = edit_name.getText().toString();
String password = edit_password.getText().toString();
#Override
public void onSuccess(DocumentSnapshot documentSnapshot)
{
if(documentSnapshot.exists())
{ // GETTING INFORMATION FROM FIRESTORE DATABASE
name = documentSnapshot.getString(KEY_NAME);
password = documentSnapshot.getString(KEY_PASSWORD);
Toast.makeText(sign_up.this, "This user already exist, Try again", Toast.LENGTH_LONG).show();
}
else
{
users.put(KEY_NAME,name);
users.put(KEY_PASSWORD, password);
db.collection("Users").document(name).set(users);
Toast.makeText(sign_up.this,"Registered",Toast.LENGTH_LONG).show();
Intent i = new Intent(sign_up.this,sum_selection.class);
startActivity(i);
}
}// END OF ONSUCCESS
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Toast.makeText(sign_up.this, "Error",Toast.LENGTH_LONG).show();
Log.d(TAG,e.toString());
}
});
Log in Activity
private MaterialEditText user_name;
private MaterialEditText user_password;
FButton sign_in;
private FirebaseFirestore database = FirebaseFirestore.getInstance();
private DocumentReference user_reference = database.document("Users/users details");
final String KEY_NAME = "name";
final String KEY_PASSWORD = "password";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
sign_in = findViewById(R.id.btn_sign_in);
sign_in.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) // log in button
{
user_reference.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>()
{
#Override
public void onSuccess(DocumentSnapshot documentSnapshot)
{
if(documentSnapshot.exists())
{
Toast.makeText(log_in.this,"Welcome"+ user_name, Toast.LENGTH_LONG).show();
// ADD INTENT TO GO TO THE SUM_SELECTION PAGE
Intent in = new Intent(log_in.this, sum_selection.class);
startActivity(in);
}
else
{
// DISPLAY ERROR MESSAGE TO USER
Toast.makeText(log_in.this, "User does not exist", Toast.LENGTH_LONG).show();
}
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
Log.d(TAG, e.toString());
}
}); ```
[Error message][1]
[1]: https://i.stack.imgur.com/8gR62.png
Intent i = new Intent((this/activity),LoginActivity.class);
(this/activity).startActivity(i);
Check your intent properly, Intent take current activity as the first param and the activity you want to load up as the second param. Also, call startActivity(i) from the activity context becuase currently you are under the context of Firebase Listener.
Also, post the error log.
I have added all the strings, private booleans in the Signup.java and properly added all the firebase dependencies. Plus, Added the codes in Login.java to retrieve all the firebase data after successful signup. However, there is no error showing in the codes but still, the sign-in screen functionalites aren't working. When I click on "Signin" button the apps showing me "This app has stopped"
Here's the code that I have written on login.java
public class Login extends AppCompatActivity {
Button callSignUp, reg_btn;
TextInputLayout username, password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
callSignUp = findViewById(R.id.signupscreen);
callSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Login.this, SignUp.class);
startActivity(intent);
}
});
//All elements Hooks
username = findViewById(R.id.reg_username);
password = findViewById(R.id.reg_password);
reg_btn = findViewById(R.id.reg_btn);
}
private Boolean validateUsername() {
String val = username.getEditText().getText().toString();
if (val.isEmpty()) {
username.setError("Please enter your username");
return false;
} else {
username.setError(null);
username.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = password.getEditText().getText().toString();
if (val.isEmpty()) {
password.setError("Please enter your password");
return false;
} else {
password.setError(null);
password.setErrorEnabled(false);
return true;
}
}
public void loginUser(View view) {
//validate user login
if (!validateUsername() | !validatePassword()) {
return;
} else {
isUser();
}
}
private void isUser() {
final String userEnteredUsername = username.getEditText().getText().toString().trim();
final String userEnteredPassword = password.getEditText().getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users");
Query checkUser = reference.orderByChild("username").equalTo(userEnteredUsername);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
username.setError(null);
username.setErrorEnabled(false);
String passwordFromDB = dataSnapshot.child(userEnteredUsername).child("password").getValue(String.class);
if (passwordFromDB.equals(userEnteredPassword)) {
String nameFromDB = dataSnapshot.child(userEnteredUsername).child("name").getValue(String.class);
String emailFromDB = dataSnapshot.child(userEnteredUsername).child("email").getValue(String.class);
String usernameFromDB = dataSnapshot.child(userEnteredUsername).child("username").getValue(String.class);
String phoneNoFromDB = dataSnapshot.child(userEnteredUsername).child("phoneNo").getValue(String.class);
Intent intent = new Intent(getApplicationContext(), UserProfile.class);
intent.putExtra("name", nameFromDB);
intent.putExtra("username", usernameFromDB);
intent.putExtra("phoneNo", phoneNoFromDB);
intent.putExtra("password", passwordFromDB);
startActivity(intent);
} else {
password.setError("Wrong Password");
}
} else {
username.setError("Opps! No Such User Exist!");
username.requestFocus();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
//Call SignUp Screen
public void callSignUpScreen(View view) {
//To call next activity
Intent intent = new Intent(Login.this, SignUp.class);
}
}
Can anyone please tell me why the issue is happening?
Thanks
I want to create login activity with multiple types of user. This login is connected with MySQL. The multiple choice is "Reviewer" and "Non-Reviewer". Now I use Spinner and the values I call from string.xml. At the table 'user', there are some column such as 'username', 'password', and 'usertype'. Example, user 'peter' is a "Reviewer", he will able to login if user name, password and user type that he uses is correct. How can i solve this problem? Below is my code.
//login activity
public class MainActivity extends AppCompatActivity{
private static final String KEY_USERNAME = "username";
private static final String LOGIN_URL = "http://lienawan.xyz/login.php";
private SharedPreferences.Editor loginPrefsEditor;
private EditText etEmail;
private EditText etPassword;
private CheckBox chkMe;
ArrayAdapter<CharSequence> adapter;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
Objects.requireNonNull(getSupportActionBar()).hide(); // hide the title ba
setContentView(R.layout.activity_main);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
chkMe = findViewById(R.id.chkMe);
SharedPreferences loginPreferences = getSharedPreferences("loginPrefs", MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
boolean saveLogin = loginPreferences.getBoolean("saveLogin", false);
if (saveLogin) {
etEmail.setText(loginPreferences.getString("username", ""));
etPassword.setText(loginPreferences.getString("password", ""));
chkMe.setChecked(true);
}
Spinner spCategory = findViewById(R.id.spCategory);
adapter = ArrayAdapter.createFromResource(this,R.array.usertype,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spCategory.setAdapter(adapter);
spCategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Button btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etEmail.getWindowToken(), 0);
String username = etEmail.getText().toString();
String password = etPassword.getText().toString();
if (chkMe.isChecked()) {
loginPrefsEditor.putBoolean("saveLogin", true);
loginPrefsEditor.putString("username", username);
loginPrefsEditor.putString("password", password);
loginPrefsEditor.apply();
} else {
loginPrefsEditor.clear();
loginPrefsEditor.commit();
}
}
});
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit");
builder.setMessage("Do you want to exit?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder.show();
}
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
userLogin(username, password);
}
private void userLogin(final String username, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
private ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Login... Please Wait",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(MainActivity.this,DashboardApp.class);
intent.putExtra(KEY_USERNAME,username);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this,s, Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
Connection ruc = new Connection();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(username, password);
}
}
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$approver = $_POST['approver'];
require_once('dbConnect.php');
$sql = "select * from user where username='$username' and password='$password'";
$check = mysqli_fetch_array(mysqli_query($con,$sql));
if(isset($check)){
echo "success";
}else{
echo "Invalid Username or Password";
}
}else{
echo "error try again";
To get selected value from spinner you write below code in onItemSelected :
String item;//declare globally out of your all method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
Now,check if item and other value are not null , like below :
private void login() {
String username = etEmail.getText().toString().trim();
String password = etPassword.getText().toString().trim();
//checking if fields are not null
if (username.isEmpty() || password.isEmpty() || item.isEmpty()) {
Toast.makeText(getActivity().getApplicationContext(), "Please enter name or pass or select one type!", Toast.LENGTH_SHORT).show();
return;
}else{
userLogin(username, password,item);//passing value to volley
}
}
And in your volley request change like below :
private void userLogin(final String username, final String password,final String item){
...
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
data.put("approver",params[2]);//adding item value
..
}
}
}
At your php side just change your query to :
$sql = "select * from user where username='$username' and password='$password' and usertype='$approver'";
Hope this helps you !
Note : Also never used plain-text password and try using prepared statement it is safe an secure.
i"m working on a project that contains a code like this one: How to add Document with Custom ID to firestore (Angular)
When I'm about to try the app, it always crashes. But the code is all the same.
The error that I get in the LogCat is this:
Invalid document reference. Document references must have an even number of segments, but Users has 1
My full code is this:
public class RegisterActivity extends AppCompatActivity {
private EditText registerUsername;
private EditText registerEmail;
private EditText registerPassword;
private EditText registerConfirmPassword;
private Button registerRegisterButton;
private Button registerLoginButton;
private ProgressBar registerProgressBar;
private FirebaseFirestore firebaseFirestore;
private String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerUsername = findViewById(R.id.register_username);
registerEmail = findViewById(R.id.register_email);
registerPassword = findViewById(R.id.register_password);
registerConfirmPassword = findViewById(R.id.register_confirm_password);
registerRegisterButton = findViewById(R.id.register_register_button);
registerLoginButton = findViewById(R.id.register_login_button);
registerProgressBar = findViewById(R.id.register_progressBar);
firebaseFirestore = FirebaseFirestore.getInstance();
user_id = registerUsername.getText().toString();
registerLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginIntent);
}
});
registerRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String username = registerUsername.getText().toString();
String email = registerEmail.getText().toString();
String password = registerPassword.getText().toString();
String confirmPassword = registerConfirmPassword.getText().toString();
if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(confirmPassword)) {
if (password.equals(confirmPassword)) {
registerProgressBar.setVisibility(View.VISIBLE);
Map<String, String> usersMap = new HashMap<>();
usersMap.put("username", username);
usersMap.put("email", email);
usersMap.put("password", password);
firebaseFirestore.collection("Users").document(user_id).set(usersMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toasty.success(RegisterActivity.this, "Successfully Registered", Toast.LENGTH_SHORT).show();
Intent loginIntent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(loginIntent);
registerProgressBar.setVisibility(View.INVISIBLE);
}
});
} else {
Toasty.error(RegisterActivity.this, "Passwords Don't Match", Toast.LENGTH_SHORT).show();
}
}
}
});
}}
I want the "user_id" to be the document id and NOT another id generated by Firestore.
Can someone please help? And Thanks in advance.
You're setting user_id at the beginning of your onCreate, probably when the EditText registerUsername doesn't contain any text. This means user_id will always be empty, no matter what happens in this activity.
You can't pass an empty string to document(). You need an actual string value there that's also a valid Firestore document ID. Try getting the string value in registerUsername after they've filled out the form, not before.
I am trying to get the current logged in user from the google firestore database
and i saw this same problem in stackoverflow of a user and i used that same method but showing blank in place user details.
Please help me Thanks.
I am earlier using querysnapshot as it gives all the users.
image description here
the image for database is
enter image description here
The code is:
public class UserProfile extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int GALLERY_INTENT = 2;
private static final String TAG = "UserProfile";
String UserId;
FirebaseAuth auth;
ImageButton Photo;
ImageView photoview;
TextView name, email, password, phone;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
if(getSupportActionBar()!=null ){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
DatabaseReference Database = FirebaseDatabase.getInstance().getReference("users");
DatabaseReference DBRef = Database.child("users");
auth = FirebaseAuth.getInstance();
UserId = auth.getCurrentUser().getUid();
FirebaseFirestore mFirestore = FirebaseFirestore.getInstance();
StorageReference mStorage = FirebaseStorage.getInstance().getReference();
FirebaseStorage storage = FirebaseStorage.getInstance();
photoview = (ImageView)findViewById(R.id.photoview);
Photo = (ImageButton)findViewById(R.id.Photoedit);
name = (TextView)findViewById(R.id.username);
email = (TextView)findViewById(R.id.useremail);
password = (TextView)findViewById(R.id.password1);
phone = (TextView)findViewById(R.id.userPhone);
mFirestore.collection("users").document(UserId).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String Name = documentSnapshot.getString("Name");
String Email = documentSnapshot.getString("Email");
String Password = documentSnapshot.getString("Password");
String Phone = documentSnapshot.getString("Phone Number");
name.setText(Name);
email.setText(Email);
password.setText(Password);
phone.setText(Phone);
}
});
Photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
}
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(UserProfile.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_INTENT);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
photoview.setImageBitmap(photo);
} else if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image ", picturePath + "");
photoview.setImageBitmap(thumbnail);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
Intent i = new Intent(UserProfile.this,category.class);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
My database structure is
Ramiki(my app name)
So here it is
Ramiki --> users(collection)--> SiQEIDaQJfUBqZBBt1eo(document uid)----> fields(Email, Name, Password, Phone Number).
Well sorry i am not able to give screenshort because i am not allowed by stack overflow 10 points needed.
And my code for writing data in firestore is
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LoginActivity";
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private TextInputEditText textInputEditTextPhone;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private FirebaseAuth auth;
private ProgressBar progressBar;
private static final int RC_SIGN_IN = 1;
private GoogleApiClient mGoogleApiClient;
private SignInButton btnSignIn;
private FirebaseFirestore mFirebaseFirestore;
private FirebaseAuth.AuthStateListener authListener;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
mFirebaseFirestore = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setPersistenceEnabled(true)
.build();
mFirebaseFirestore.setFirestoreSettings(settings);
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
}
};
btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
btnSignIn.setOnClickListener(this);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// Customizing G+ button
btnSignIn.setSize(SignInButton.SIZE_STANDARD);
btnSignIn.setScopes(gso.getScopeArray());
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
appCompatTextViewLoginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(LoginActivity.this, account.class);
startActivity(i);
finish();
}
});
//if the user is already logged in we will directly start the category activity
if (SavesharedPreferences.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, category.class));
finish();
return;
}
findViewById(R.id.appCompatButtonRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
progressBar.setVisibility(View.VISIBLE);
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("Name", Name);
user.put("Email", Email);
user.put("Password", Password);
user.put("Phone Number", Phone_Number);
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if(Password.length() < 7){
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else if (!textInputEditTextPassword.getText().toString().equals(textInputEditTextConfirmPassword.getText().toString())) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
progressBar.setVisibility(View.GONE);
}
else {
// Add a new document with a generated ID
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
registerUser();
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
}
}
});
initViews();
}
#Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.btn_sign_in:
signIn();
break;
}
}
private void registerUser() {
final String Name = textInputEditTextName.getText().toString().trim();
final String Email = textInputEditTextEmail.getText().toString().trim();
final String Password = textInputEditTextPassword.getText().toString().trim();
final String Phone_Number = textInputEditTextPhone.getText().toString().trim();
final String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(Name)) {
textInputEditTextName.setError("Please enter name");
textInputEditTextName.requestFocus();
return;
}
if (TextUtils.isEmpty(Email)) {
textInputEditTextEmail.setError("Please enter your email");
textInputEditTextEmail.requestFocus();
return;
}
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
textInputEditTextEmail.setError("Email already exist");
textInputEditTextEmail.requestFocus();
return;
}
if (TextUtils.isEmpty(Password)) {
textInputEditTextPassword.setError("Enter a password");
textInputEditTextPassword.requestFocus();
return;
}
if(Password.length() < 7 ) {
textInputEditTextPassword.setError("Paasword must be greater than 7 digits");
textInputEditTextPassword.requestFocus();
return;
}
if (TextUtils.isEmpty(ConfirmPassword)) {
textInputEditTextPassword.setError("Password Doesn't Match");
textInputEditTextPassword.requestFocus();
return;
}
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(LoginActivity.this, "Register Successful " + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()){
sendEmailVerification();
}
// 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.
else if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LoginActivity.this, "Nothing Happens", Toast.LENGTH_SHORT).show();
}
}
});
}
private void sendEmailVerification() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(LoginActivity.this,"Please Check Your Email For Verification",Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(LoginActivity.this, account.class));
finish();
}
}
});
}
}
#Override
protected void onResume() {
super.onResume();
progressBar.setVisibility(View.GONE);
}
private void initViews() {
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextPhone = (TextInputEditText) findViewById(R.id.textInputEditTextPhone);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(LoginActivity.this, "You Got an Error",Toast.LENGTH_LONG).show();
}
protected void onStart(){
super.onStart();
auth.addAuthStateListener(authListener);
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
FirebaseUser user = auth.getCurrentUser();
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
}
This unique id SiQEIDaQJfUBqZBBt1eo is generated when you are adding the user as a Map or when you are using a call to document() method without passing an argument.
In order to solve this, there are two ways. One would be to create a model class (UserModel), then create an object of that class and in the end get the uid of the user once it authenticated and add the object to the database like this:
String Name = textInputEditTextName.getText().toString().trim();
String Email = textInputEditTextEmail.getText().toString().trim();
String Password = textInputEditTextPassword.getText().toString().trim();
String Phone_Number = textInputEditTextPhone.getText().toString().trim();
String ConfirmPassword = textInputEditTextConfirmPassword.getText().toString().trim();
UserModel userModel = new UserModel(Name, Email, Password, Phone_Number, ConfirmPassword);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference usersRef = rootRef.collection("users");
usersRef.document(uid).set(userModel);
See, I have passed the uid as argument to the document() method.
The second approach would be to pass no argument to the document() method but to store that key into a variable like this:
String key = usersRef.document().getKey();
usersRef.document(key).set(userModel);
Edit:
There also another method, which I recommend you use it. Instead of using this line of code:
mFirebaseFirestore.collection("users")
.add(user)
.addOnSuccessListener(/* ... */)
Use the following line of code:
mFirebaseFirestore.collection("users")
.document(uid)
.set(user)
.addOnSuccessListener(/* ... */)
Remove the old data, add fresh one and your problem will be solved.