"I just started learning Firebase"
I did set callbacks in PhoneAuthOptions yet I keep getting the error:
java.lang.NullPointerException: You must specify callbacks on your PhoneAuthOptions. Please call #setCallbacks().
This is my first activity, from which I am getting user's phone number and passing it to second activity:
public class SendOTPActivity extends AppCompatActivity {
private EditText mPhoneNumber;
private Button mBtnSendOtp;
String phoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_o_t_p);
mPhoneNumber = findViewById(R.id.phone_number);
mBtnSendOtp = findViewById(R.id.btn_send_otp);
phoneNumber = mPhoneNumber.getText().toString();
mBtnSendOtp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),VerifyOTPActivity.class);
intent.putExtra("PHONE_NUMBER",phoneNumber);
startActivity(intent);
mBtnSendOtp.setEnabled(false);
}
});
}
}
This is second activity (Verification Activity):
public class VerifyOTPActivity extends AppCompatActivity {
private EditText mOtpCode;
private Button mBtnVerifyOtp;
private TextView textView;
private ProgressBar progressBar;
private String phoneNumber;
private String code;
private FirebaseAuth mAuth;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_o_t_p);
mAuth = FirebaseAuth.getInstance();
mOtpCode = findViewById(R.id.otp_code);
mBtnVerifyOtp = findViewById(R.id.btn_verify_otp);
textView = findViewById(R.id.text_view);
progressBar = findViewById(R.id.progress_bar);
phoneNumber = getIntent().getStringExtra("PHONE_NUMBER");
code = mOtpCode.getText().toString();
textView.setText("An OTP has been sent to +91 "+phoneNumber);
startPhoneNumberVerification(phoneNumber);
mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code!=null){
progressBar.setVisibility(View.VISIBLE);
}
signInWithPhoneAuthCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
if (e instanceof FirebaseAuthInvalidCredentialsException) {
// Invalid request
Toast.makeText(VerifyOTPActivity.this, "Provided phone number might not be correct", Toast.LENGTH_SHORT).show();
} else if (e instanceof FirebaseTooManyRequestsException) {
// The SMS quota for the project has been exceeded
Toast.makeText(VerifyOTPActivity.this, "Some error has occurred please try again later!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken token) {
mVerificationId = s;
mResendToken = token;
}
};
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
mAuth.signInWithCredential(phoneAuthCredential)
.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
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
FirebaseUser user = task.getResult().getUser();
// Update UI
} else {
// Sign in failed, display a message and update the UI
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
Toast.makeText(VerifyOTPActivity.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
// The verification code entered was invalid
}
}
}
});
}
private void startPhoneNumberVerification(String phoneNumber){
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+91"+phoneNumber)
.setTimeout(60L, TimeUnit.SECONDS)
.setActivity(this)
.setCallbacks(mCallbacks)
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
In onCreate you call startPhoneNumberVerification(phoneNumber); before you create your OnVerificationStateChangedCallbacks. Try to move startPhoneNumberVerification(phoneNumber); below the block where you create your callback. That should get rid of the NullPointerException.
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'm new to android and now I'm working on making users to login using their facebook and gmail things going well but i need to know how do make the user to signout from the app and login in the user with new accounts. i tried a lot of tutorials but none of them are not as i thought and expected. The user when clicks on logout button from another activity and comebacks to login activity.
example: when user logins from UserAction.class the logout button is in ProfileFragment.class
I tried a lot but haven't found any solution any help.
Code i Tried
public class UserAction extends AppCompatActivity {
private CallbackManager callbackManager;
public LoginButton loginButton;
private static final String EMAIL = "email";
private SignInButton signInButton;
GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
private int RC_SIGN_IN = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_action);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
signInButton = findViewById(R.id.gmail_login_button);
mAuth = FirebaseAuth.getInstance();
GoogleSignInOptions gsp = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gsp);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GmailLogin();
}
private void GmailLogin() {
Intent mailSignIn = mGoogleSignInClient.getSignInIntent();
startActivityForResult(mailSignIn,RC_SIGN_IN);
}
});
AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();
AppEventsLogger.activateApp(getApplication());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.fb_login_button);
loginButton.setReadPermissions(Arrays.asList(EMAIL));
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Intent intent = new Intent(UserAction.this, AppMain.class);
startActivity(intent);
}
#Override
public void onCancel() {
// App code
}
#Override
public void onError(FacebookException exception) {
// App code
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN){
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void handleSignInResult(Task<GoogleSignInAccount> CompletedTask) {
try {
GoogleSignInAccount account = CompletedTask.getResult(ApiException.class);
Toast.makeText(this, "Signed in Successfully", Toast.LENGTH_SHORT).show();
FirebaseGoogleAuth(Objects.requireNonNull(account));
} catch (ApiException e) {
ConstraintLayout UserAction = findViewById(R.id.userAction);
Snackbar snackbar = Snackbar.make(UserAction,"Login Failed Please try Again.", Snackbar.LENGTH_SHORT);
snackbar.show();
FirebaseGoogleAuth(null);
}
}
private void FirebaseGoogleAuth(final GoogleSignInAccount account) {
AuthCredential authCredential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(authCredential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
FirebaseUser user = mAuth.getCurrentUser();
GoogleSignInAccount googleSignInAccount = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
String personName = Objects.requireNonNull(googleSignInAccount).getDisplayName();
String personEmail = googleSignInAccount.getEmail();
String personId = googleSignInAccount.getId();
Toast.makeText(UserAction.this, personName+ "\n" +personEmail + "\n" + personId , Toast.LENGTH_SHORT).show();
}
}
});
}
}
To sign out from Firebase use
mAuth.signOut();
And to sign out from google client use
mGoogleSignInClient.signOut()
After I log in the first time and log out, the next time I log in I don't get an OTP.
How do I solve this problem??
The code works fine if I enter the phone number for the first time. Second time onwards I am not getting OTP number. In order to get the OTP number, I need to restart my phone each time. If I close and reopen the app then it's not helping me too.
VerifyPhoneActivity
public class VerifyPhoneActivity extends AppCompatActivity {
private String verificationId;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_verify_phone);
mAuth = FirebaseAuth.getInstance();
editText = findViewById(R.id.editTextCode);
progressBar =findViewById(R.id.progressbar);
String phonenumber = getIntent().getStringExtra("phonenumber");
setVerificationCode(phonenumber);
findViewById(R.id.buttonSignIn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String code = editText.getText().toString().trim();
if(code.isEmpty() || code.length()< 6){
editText.setError("Enter code");
editText.requestFocus();
return;
}
verifyCode(code);
}
});
}
private void verifyCode(String code){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);
SignInWithCredential(credential);
}
private void SignInWithCredential(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent intent = new Intent(VerifyPhoneActivity.this, ProfileActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else {
Toast.makeText(VerifyPhoneActivity.this, task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
private void setVerificationCode(String number){
progressBar.setVisibility(View.VISIBLE);
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks
mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationId = s;
}
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code =phoneAuthCredential.getSmsCode();
if(code != null){
editText.setText(code);
SignInWithCredential(phoneAuthCredential);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(VerifyPhoneActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
};
You should read docs if mobile gets registered on firebase it won't send OTP all time, maybe few times.
Once mobile is registered you will get success and then you can verify.
I am completely noob (again sorry about my ignorance in this field I relly need help) in java and I need to make an app with firebase. Here is my register account code(its all the code I have copied from GitHub :P) I want to make it just to register with username, the register with email and password functionality and the verification sending future completely to be disabled , also I need to make it to go on a different activity or simply to login the user and show the posts feed. I hope someone could help me:
public class SignupActivity extends BaseActivity {
private static final String TAG = "SignupActivity";
private Context mContext = SignupActivity.this;
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FireBaseMethods fireBaseMethods;
private String email, handleName, password;
private EditText mHandleName, mEmail, mPassword;
private Button mButtonRegister;
private TextView loadingPleaseWait;
private ProgressBar mProgressBar;
//firebase Database
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
boolean isExisted;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
fireBaseMethods = new FireBaseMethods(mContext);
Log.d(TAG, "onCreate: started");
initWidgets();
setupFirebaseAuth();
init();
}
#Override
protected void performOnCreate(Bundle state) {
}
private void init() {
mButtonRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleName = mHandleName.getText().toString();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(mEmail.getText().toString());
stringBuilder.append("");
email = stringBuilder.toString();
password = mPassword.getText().toString();
if (validate()) {
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
fireBaseMethods.registerNewEmail(handleName, email, password);
}
}
});
}
/*
Initialize the activity widgets
*/
private void initWidgets() {
Log.d(TAG, "initWidgets: Initialize Widgets");
mHandleName = findViewById(R.id.handle_name);
mEmail = findViewById(R.id.input_email_signup);
mPassword = findViewById(R.id.input_password_signup);
mButtonRegister = findViewById(R.id.btn_signup);
mProgressBar = findViewById(R.id.progressBar);
loadingPleaseWait = findViewById(R.id.loading_signup);
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
public boolean validate() {
boolean valid = true;
if (handleName.isEmpty() || handleName.length() < 3) {
mHandleName.setError("Внесете најмалку 3 карактери");
valid = false;
} else {
mHandleName.setError(null);
}
if (email.isEmpty()) {
mEmail.setError("Внесете валидна електронска пошта");
valid = false;
} else {
mEmail.setError(null);
}
if (password.isEmpty() || password.length() < 4) {
mPassword.setError("помеѓу 4 и 10 карактери");
valid = false;
} else {
mPassword.setError(null);
}
return valid;
}
/*
------------------------------------- Firebase ---------------------------------------------------
*/
/**
* Set up firebase auth object
*/
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
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());
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//1st check: make sure handle name is not ready in use
if (fireBaseMethods.checkIfHandleNameAlreadyExists(handleName, dataSnapshot)) {
mHandleName.setError("Тој ник веќе постои");
isExisted = true;
}
//add new user to the database
fireBaseMethods.addNewUser(handleName, email);
Toast.makeText(mContext, "Регистрирањето беше успешно.Ви пративме верификација на email", Toast.LENGTH_SHORT).show();
mAuth.signOut();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
finish();
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
I do NOT advise the ability to sign up with ONLY a username. You lose the ability to recover an account.
However, you may take the username given to you, and append #fakeemail.com to the end of it and continue to use the email/password method.
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.