Cannot resolve method 'setTimestampsInSnapshotsEnabled' in 'Builder' - java

I am trying to create a register activity to allow a user to register however I keep getting the error:
Cannot resolve method 'setTimestampsInSnapshotsEnabled' in 'Builder'"
It's only the section which has the setTimestampsInSnapshotsEnabled that is giving me the issue. Do I need an implementation?
Here is my Java code:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener
{
private static final String TAG = "RegisterActivity";
//widgets
private EditText mEmail, mPassword, mConfirmPassword;
private ProgressBar mProgressBar;
//vars
private FirebaseFirestore mDb;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mEmail = (EditText) findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mConfirmPassword = (EditText) findViewById(R.id.input_confirm_password);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
findViewById(R.id.btn_register).setOnClickListener(this);
mDb = FirebaseFirestore.getInstance();
hideSoftKeyboard();
}
/**
* Register a new email and password to Firebase Authentication
* #param email
* #param password
*/
public void registerNewEmail(final String email, String password){
showDialog();
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
if (task.isSuccessful()){
Log.d(TAG, "onComplete: AuthState: " + FirebaseAuth.getInstance().getCurrentUser().getUid());
//insert some default data
User user = new User();
user.setEmail(email);
user.setUsername(email.substring(0, email.indexOf("#")));
user.setUser_id(FirebaseAuth.getInstance().getUid());
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
mDb.setFirestoreSettings(settings);
FirebaseFirestoreSettings newUserRef = mDb
.collection(getString(R.string.collection_users))
.document(FirebaseAuth.getInstance().getUid());
newUserRef.set(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
hideDialog();
if(task.isSuccessful()){
redirectLoginScreen();
}else{
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "Something went wrong.", Snackbar.LENGTH_SHORT).show();
}
}
});
}
else {
View parentLayout = findViewById(android.R.id.content);
Snackbar.make(parentLayout, "Something went wrong.", Snackbar.LENGTH_SHORT).show();
hideDialog();
}
// ...
}
});
}
/**
* Redirects the user to the login screen
*/
private void redirectLoginScreen(){
Log.d(TAG, "redirectLoginScreen: redirecting to login screen.");
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private void showDialog(){
mProgressBar.setVisibility(View.VISIBLE);
}
private void hideDialog(){
if(mProgressBar.getVisibility() == View.VISIBLE){
mProgressBar.setVisibility(View.INVISIBLE);
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_register:{
Log.d(TAG, "onClick: attempting to register.");
//check for null valued EditText fields
if(!isEmpty(mEmail.getText().toString())
&& !isEmpty(mPassword.getText().toString())
&& !isEmpty(mConfirmPassword.getText().toString())){
//check if passwords match
if(doStringsMatch(mPassword.getText().toString(), mConfirmPassword.getText().toString())){
//Initiate registration task
registerNewEmail(mEmail.getText().toString(), mPassword.getText().toString());
}else{
Toast.makeText(RegisterActivity.this, "Passwords do not Match", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RegisterActivity.this, "You must fill out all the fields", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}

If I look at the current documentation for FirebaseFirestoreSettings.Builder, I don't see any setTimestampsInSnapshotsEnabled method. So that probably explains the error message: you're trying to call a method that doesn't exist.
My guess is that your code was meant for an older version of the SDK when the method did exist. Since it doesn't exist anymore now, you either have to use the version of the SDK that the code was made for, or remove the call.
Update: it looks like timestampsInSnapshotsEnabled was removed in version 22 of the Android SDK for Firestore back in October 2020.

Related

Can we show the login information made with the firebase authentication system as textview in the application?

I have created a login-register system by using Firebase auth. Now I want to show the registration information (name, email, phone) in my app. I want to reflect the registration information to text view but I couldn't find the way to do that.
Registration class:
public class RegisterActivity extends AppCompatActivity {
EditText mName, mEmail, mPassword, mPhone;
Button mRegisterButton;
TextView mLoginButton;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mName = findViewById(R.id.userName);
mEmail = findViewById(R.id.userMail);
mPassword = findViewById(R.id.userPassword);
mPhone = findViewById(R.id.userPhone);
mRegisterButton = findViewById(R.id.register_button);
mLoginButton = findViewById(R.id.goToLogin);
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
if(TextUtils.isEmpty(email))
{
mEmail.setError("Email is required");
return;
}
if(TextUtils.isEmpty(password))
{
mPassword.setError("Password is required");
return;
}
if(password.length() < 0)
{
mPassword.setError("Password Must Be >= 6 Characters");
return;
}
firebaseAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this, "User Created.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = firebaseAuth.getCurrentUser();
}else{
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(RegisterActivity.this, "Error!" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
mLoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
}
});
}
}
Assuming that you have a TextView added in your layout, especially added to display the data, then right after the following line of code:
FirebaseUser user = firebaseAuth.getCurrentUser();
Add these lines:
String name = user.getDisplayName();
String email = user.getEmail();
TextView textView = findViewById(R.id.textViewId);
String text = name + "/" + email;
textView.setText(text);
Please also note that when you are using email and password authentication the phone number doesn't exist. So if you try to use it, you'll get null.
Kotlin code below;
fun onCreate(savedInstanceState: Bundle) {
val curreentUser = FirebaseAuth.getInstance().currentUser
val name = currentUser?.displayName
val email = currentUser?.email
val phone = currentUser?.phoneNumber
val textView = findViewById(R.id.your_text_view_id)
textView.text = "$name, $email, $phone"
}

onCreate() is not running when i switch to the activity or onDataChanged is getting called first

i am working on a school project and i am using firebase authentication with email and password. i have a problem when a user sing in, then returns to the sing in page and tries to create a new account. when clicking the submit button to create his new account instead of going back to the sign in page, it goes to the users main page. this only happens if a user has already singed in and then tries to sign up another account. i have tried signin out the user when he is returning to the sign in page but it didnt work. here is my code:
sign in page:
public class SignIn extends AppCompatActivity {
EditText email,pass;
private FirebaseAuth mAuth;
FirebaseUser user;
FirebaseDatabase db;
DatabaseReference mRef;
String type,name;
public ProgressDialog pd;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
mAuth = FirebaseAuth.getInstance();
email = findViewById(R.id.inpSigninEmail);
pass = findViewById(R.id.inpSigninPass);
db.getInstance();
mRef = FirebaseDatabase.getInstance().getReference().child("Users/");
type=null;
name=null;
context=this;
Log.e("asd","Loginoncreate");
}
public void signIn (View view){
if (email.getText().toString().trim().length() < 1 || pass.getText().toString().trim().length() < 1){
Toast.makeText(getApplicationContext(), "Please fill your information.", Toast.LENGTH_LONG).show();
}else{
pd = new ProgressDialog(this);
pd.setMessage("Signing in...");
pd.show();
mAuth.signInWithEmailAndPassword(email.getText().toString(), pass.getText().toString()).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
user = mAuth.getCurrentUser();
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
while (type==null){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
type = String.valueOf(dataSnapshot.child(user.getUid()).child("/Type").getValue());
if (type!="null"){
break;
}
}
}
while (name==null){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
name = String.valueOf(dataSnapshot.child(user.getUid()).child("/Name").getValue());
if (name!="null"){
break;
}
}
}
pd.dismiss();
if (type.matches("user")){
Intent intent = new Intent(context, UserMain.class);
intent.putExtra("name", name);
type=null;
name=null;
startActivity(intent);
finish();
Log.e("as","loginUser");
}else{
Intent intent = new Intent(context, CompanyMain.class);
intent.putExtra("name", name);
startActivity(intent);
finish();
type=null;
name=null;
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
pd.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else{
pd.dismiss();
Toast.makeText(getApplicationContext(), task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
}
public void signUp (View view){
startActivity(new Intent(SignIn.this, SignUp.class));
finish();
}
}
sign up page:
public class SignUp extends AppCompatActivity {
EditText name,email,pass;
private FirebaseAuth mAuth;
FirebaseDatabase db;
FirebaseUser user;
RadioButton Rbtn;
RadioGroup Rgroup;
DatabaseReference mRef;
boolean out = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
mAuth = FirebaseAuth.getInstance();
name = findViewById(R.id.inpSignupName);
email = findViewById(R.id.inpSignupEmail);
pass = findViewById(R.id.inpSignupPass);
Rgroup = findViewById(R.id.radioGroup);
db = FirebaseDatabase.getInstance();
mRef = db.getReference("Users/");
Log.e("asd","Signuponcreate");
}
public void submit (View view){
if (name.getText().toString().trim().length() < 1 || email.getText().toString().trim().length() < 1 || pass.getText().toString().trim().length() < 1){
Toast.makeText(getApplicationContext(), "Please fill your information.", Toast.LENGTH_LONG).show();
}else{
mAuth.createUserWithEmailAndPassword(email.getText().toString() , pass.getText().toString()).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Sign Up success!",Toast.LENGTH_LONG).show();
user = mAuth.getCurrentUser();
int radioId = Rgroup.getCheckedRadioButtonId();
Rbtn = findViewById(radioId);
if (Rbtn.getText().equals("User")){
mRef.child("/Normal").child(user.getUid()).child("/Name").setValue(name.getText().toString());
mRef.child("/Normal").child(user.getUid()).child("/Type").setValue("user");
}else{
mRef.child("/Company").child(user.getUid()).child("/Name").setValue(name.getText().toString());
mRef.child("/Company").child(user.getUid()).child("/Type").setValue("company");
}
startActivity(new Intent(SignUp.this, SignIn.class));
finish();
Log.e("as","signupUserGotoSignin");
}else{
Toast.makeText(getApplicationContext(), task.getException().getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
}
}
and here are my logs:
E/asd: Loginoncreate (this is the first message i see and its when i start up the app,then i sign in and go to user main page)
E/as: loginUser (when i sign in the first time while the is opened and go to users main page)
E/asd: Loginoncreate (When i return from the users main page)
E/asd: Signuponcreate (i go to create a new account)
E/as: signupUserGotoSignin (i create the account and want to return to the sign in page)
E/as: loginUser (here i would expect the Loginoncreate message again but i never get it, i always get this message 2 times. this message is onDataChanged)
E/as: loginUser
after i click the submit button to create the new account it never returns to the sign in page. i know that firebase is asynchronous but i dont know what i am doing wrong here. why the onCreate on sign in page never gets called and it goes immediately in the onDataChanged and takes me to the users main page?
I assume that signIn (View view) method is your signIn button click event. So,
firstly, you need to remove onClick attribute from button XML code.
android:onClick="signIn"
then, create onClick button event in onCreate() method.
Like,
Button button = findViewById(R.id.SignInbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//put your signIn button all code here
}
});
The same thing does in the SignUp page activity.
Okay so i put everything i have inside the onDataChange under an If statement where i check temp variable if its true, and right before i am move the user to the users main page i make that variable false. this fixed my problem but if someone have an explanation on why this was happening before i would still appreciate it. thanks

User credentials are not getting stored in firebase database

While registering for user, it is getting failed and gives exception in logcat as
" I/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms: com.google.firebase.auth.api.internal.zzaq#1a8a2b0 "
All the correct and updated dependencies are implemented.....
While clicking on signup button on android studio it is getting failed and gives the message as "Failed while registering, An internal error has occurred [7 :]"
public class RegistrationActivity extends AppCompatActivity
{
private EditText email;
private EditText password;
private TextView signIn;
private Button registerBtn;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration);
firebaseAuth = FirebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
email = findViewById(R.id.email_register);
password = findViewById(R.id.password_register);
registerBtn = findViewById(R.id.btn_register);
signIn = findViewById(R.id.sign_in_txt);
registerBtn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
String myEmail = email.getText().toString().trim();
String myPass = password.getText().toString().trim();
if (TextUtils.isEmpty(myEmail))
{
email.setError("This field is required.");
return;
}
if (TextUtils.isEmpty(myPass))
{
password.setError("This field is required.");
return;
}
progressDialog.setMessage("Registering please wait...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(myEmail, myPass).addOnCompleteListener(RegistrationActivity.this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
startActivity(new Intent(getApplicationContext(), HomeActivity.class));
Toast.makeText(getApplicationContext(), "Successfully Registered...", Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
else
{
Toast.makeText(getApplicationContext(), "Failed while registering..." + task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressDialog.dismiss();
}
}
});
}
});
signIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
}

How to register user into firebase registration?

I am going to insert my email and password into Firebase Authentication. However, the code that I found on the Internet does not work for me? Below is the code and when I click next button, it goes back to the previous page too, it does not proceed with the next page?
public void completeRegis() {
username1 = username.getText().toString().trim();
email1 = email.getText().toString().trim();
psd1 = psd.getText().toString().trim();
psd2 = reconpsd.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email1, psd1)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//start profile activity here
User user = new User(username1, email1,psd1);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RoleInfo1.this, "Registration successful.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RoleInfo1.this, HomePage.class ));
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RoleInfo1.this, "Database not created", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RoleInfo1.this, "Registration not successful, please try again.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void initializeUI() {
username = findViewById(R.id.usernameregister);
email = findViewById(R.id.emailregister);
psd = findViewById(R.id.psdregister);
reconpsd = findViewById(R.id.reconpsdregister);
progressBar = findViewById(R.id.progressBar);
}
}
I am very new to android but I recently made a signUp page successfully.
declare a firebase auth instance
private FirebaseAuth mAuth;
private EditText mName, mEmailField, mConfirmPass, mNewPass;
then in onCreate() I declared them as
mName = (EditText) findViewById(R.id.eName);
mEmailField = (EditText) findViewById(R.id.fieldEmail);
mConfirmPass = (EditText) findViewById(R.id.fieldConfirm);
mNewPass = (EditText) findViewById(R.id.fieldNew);
mAuth = FirebaseAuth.getInstance();
I added a button in the authentication page for signup. Clicking on it starts the signUp procedure. This is done in onCreate() method
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startSignUp();
}
});
Then I declare the startSignUp() method as below
public void startSignUp(){
String name = mName.getText().toString();
String email = mEmailField.getText().toString();
String newPass = mNewPass.getText().toString();
String conPass = mConfirmPass.getText().toString();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(email) || TextUtils.isEmpty(newPass) || TextUtils.isEmpty(conPass)){
Toast.makeText(SignUp.this, "Fields Empty" , Toast.LENGTH_LONG).show();
}
mAuth.createUserWithEmailAndPassword(email,newPass).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(! task.isSuccessful()){
Toast.makeText(SignUp.this, "SignUp Failed", Toast.LENGTH_LONG).show();
}else {
openAuthetication();
}
}
});
}
}
If signUp is successful, it will go back to the authentication page for signing in. This is done in the openAuthetication() method.
public void openAuthetication(){
Intent intent = new Intent(this, Authetication.class);
startActivity(intent);
}

Android Firebase Error at Creating Users

I am trying to make a Firebase Chat application and I can't seem to find the reason why I get the error when I am creating users. In the Firebase Console, Sign-In Method is Enabled on Email/Password.
I have tried:
-Introducing users from the Firebase console, that works
-Introducing legit credentials, so I won't raise up invalid password, username, email errors
-I tried using the code provided by the Android Assistant Firebase, the same error is given to me
Could someone point where I may be wrong?
public class RegisterActivity extends AppCompatActivity {
private TextInputLayout mDisplayName;
private TextInputLayout mEmail;
private TextInputLayout mPassword;
private Button mCreateBtn;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mAuth = FirebaseAuth.getInstance();
mDisplayName = (TextInputLayout) findViewById(R.id.reg_display_name);
mEmail = (TextInputLayout) findViewById(R.id.reg_email);
mPassword = (TextInputLayout) findViewById(R.id.reg_password);
mCreateBtn = (Button) findViewById(R.id.reg_create_btn);
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String display_name = mDisplayName.getEditText().getText().toString();
String email = mEmail.getEditText().getText().toString();
String password = mPassword.getEditText().getText().toString();
register_user(display_name, email, password);
}
});
}
private void register_user(String display_name, String email, String password) {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Intent mainIntent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
else {
Toast.makeText(RegisterActivity.this, "You got some error with creating the new user.", Toast.LENGTH_LONG).show();
}
}
});
}
}
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(), Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
Try this one I think you have forgotten addOnCompleteListener(Executor executor, OnCompleteListener listener), the Executor determines the thread that will be used to invoke the listener.

Categories