implementing clean architecture with realtime Firebase in AndroidStudio - java

Hi I want to implement clean architecture while using the realtime database but is seems that it is impossible to seperate the database from the my account screen class. Ideally I would want a DatabaseManager class that would handle all database operation (getting reading and posting to the db) but it seems that because the AuthStateChangeListener needs to be in the oncreate of my files it can't work. Does anyone know of any work-arounds? Here is the code I am using this on:
public class CreateAccountScreen extends AppCompatActivity {
private Button mRegister;
private EditText mEmail, mPassword, mCPassword, mName;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener firebaseAuthStateListener;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.create_account);
//------------------------------------------------------
//I would want to put this in a seperate class
//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//------------------------------------------------------
mAuth = FirebaseAuth.getInstance();
firebaseAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user !=null){
Intent intent = new Intent(CreateAccountScreen.this, HomeScreen.class);
startActivity(intent);
finish();
return;
}
}
};
//-----------------------------------------------------
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//I would want this in a seperate class
//------------------------------------------------------
mRegister = (Button) findViewById(R.id.goSignIn2);
mEmail = (EditText) findViewById(R.id.username3);
mPassword = (EditText) findViewById(R.id.password2);
mCPassword = (EditText) findViewById(R.id.password3);
mName = (EditText) findViewById(R.id.username2);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
final String cPassword = mCPassword.getText().toString();
final String name = mName.getText().toString();
if (name.equals("") || password.equals("") || email.equals("") || !password.equals(cPassword)) {
Toast.makeText(CreateAccountScreen.this, "sign up error", Toast.LENGTH_SHORT).show();
return;
}
//------------------------------------------------------
//I would want to also put this in a seperate class
//VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
//------------------------------------------------------
//DatabaseManager.createUser(email, password, name, CreateAccountScreen.this);
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(CreateAccountScreen.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful()) {
Toast.makeText(CreateAccountScreen.this, "sign up error", Toast.LENGTH_SHORT).show();
}else{
String userId = mAuth.getCurrentUser().getUid();
DatabaseReference currentUserDb = FirebaseDatabase.getInstance().getReference().child("Users").child(userId);
DatabaseReference currentUserDb2 = FirebaseDatabase.getInstance().getReference().child("Users").child(userId).child("connections").child("no").child(userId);
Map userInfo = new HashMap<>();
userInfo.put("name", name);
userInfo.put("profileImageUrl", "default");
currentUserDb2.setValue(true);
currentUserDb.updateChildren(userInfo);
}
}
});
//-----------------------------------------------------
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//I would want this in a seperate class
//------------------------------------------------------
}
});
}
}

Related

Firebase Database users is not created-android

The register section of my app, android, is working fine. It creates a new users in the firebase database authentication section. However, i am unable to create a user's database. I do not get any error. The app works fine except that it does not create the user section in my firebase database. Any reason and solution for that?
Code
public class Register extends AppCompatActivity {
Button btnReg;
EditText name,email,pass1,pass2,phone;
FirebaseAuth fAuth;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
fAuth = FirebaseAuth.getInstance();
name =(EditText) findViewById(R.id.fullName);
email = (EditText) findViewById(R.id.mail);
pass1 = (EditText) findViewById(R.id.password);
pass2 = (EditText) findViewById(R.id.password2);
btnReg = (Button) findViewById(R.id.btnRegister);
phone=(EditText)findViewById(R.id.txtPhone);
ActionBar actionBar=getSupportActionBar();
if(actionBar!=null)
{
actionBar.setTitle("Register User");
}
//code for register button
btnReg.setOnClickListener(v -> {
final String userEmail=email.getText().toString();
final String userFullName=name.getText().toString();
final String userPassword1=pass1.getText().toString().trim();
final String userPassword2=pass2.getText().toString().trim();
final String userPhoneNumber=phone.getText().toString().trim();
if(TextUtils.isEmpty(userEmail))
{
email.setError("Enter Email");
}
if(TextUtils.isEmpty(userFullName))
{
name.setError("Enter Full Name");
}
if(TextUtils.isEmpty(userPassword1))
{
pass1.setError("Enter Password");
}
if(TextUtils.isEmpty(userPassword2))
{
pass2.setError("Enter Password");
}
if(TextUtils.isEmpty(userPhoneNumber))
{
phone.setError("Enter your phone number");
}
if(userPassword2.length()<6)
{
pass1.setText("");
pass1.setError("PassWord should greater than 6 characters");
}
if(userPassword2.length()<6)
{
pass2.setText("");
pass2.setError("PassWord should greater than 6 characters");
}
else
{
if(userPassword1.equals(userPassword2)) {
registerUser(userFullName, userEmail, userPassword1, userPassword2);
}
}
});
}
private void registerUser(final String userFullName,final String userEmail,final String pass1,final String phone) {
fAuth.createUserWithEmailAndPassword(userEmail,userFullName).addOnCompleteListener(Register.this, task -> {
if(task.isSuccessful()){
FirebaseUser firebaseUser= fAuth.getCurrentUser();
String id=firebaseUser.getUid();
databaseReference=FirebaseDatabase.getInstance().getReference().child("users").child(id);
HashMap<String,Object>hashMap=new HashMap<>();
hashMap.put("id",id);
hashMap.put("userName",userFullName.toLowerCase());
hashMap.put("Email",email);
hashMap.put("Password",pass1);
hashMap.put("PhoneNumber",phone);
databaseReference.setValue(hashMap).addOnCompleteListener(task1 -> {
if(task1.isSuccessful())
{
Intent intent=new Intent(Register.this,MainActivity.class);
Toast.makeText(Register.this,"Account Created!",Toast.LENGTH_SHORT).show();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
else
{
Toast.makeText(Register.this,"FAILED TO CREATE ACCOUNT"+task.getException().getMessage().toString(),Toast.LENGTH_SHORT).show();
}
});
}
}

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"
}

Android application won't go the next activity from the log in or sign up activity

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.

android - Adding a Custom ID to Firestore document

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.

App stops working when register button is clicked

i want to register then when clicked on register button a verification email is sent to the email address.on clicking the link in the email.the email is verified.and the user can now login from the login screen.
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private static final String TAG = "RegisterActivity";
private Context mContext;
private String email, username, password;
private EditText mEmail, mPassword, mUsername;
private TextView loadingPleaseWait;
private Button btnRegister;
private ProgressBar mProgressBar;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseMethods firebaseMethods;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String append = "";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mContext = RegisterActivity.this;
//mAuth = FirebaseAuth.getInstance();
firebaseMethods = new FirebaseMethods(mContext);
Log.d(TAG, "onCreate: started.");
initWidgets();
setupFirebaseAuth();
init();
}
private void init(){
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
email = mEmail.getText().toString();
username = mUsername.getText().toString();
password = mPassword.getText().toString();
if(checkInputs(email, username, password)){
mProgressBar.setVisibility(View.VISIBLE);
loadingPleaseWait.setVisibility(View.VISIBLE);
firebaseMethods.registerNewEmail(email, password, username);
}
}
});
}
private boolean checkInputs(String email, String username, String password){
Log.d(TAG, "checkInputs: checking inputs for null values.");
if(email.equals("") || username.equals("") || password.equals("")){
Toast.makeText(mContext, "All fields must be filled out.", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
private void initWidgets(){
Log.d(TAG, "initWidgets: Initializing Widgets.");
mEmail = (EditText) findViewById(R.id.input_email);
mUsername = (EditText) findViewById(R.id.input_username);
btnRegister = (Button) findViewById(R.id.btn_register);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
loadingPleaseWait = (TextView) findViewById(R.id.loadingPleaseWait);
mPassword = (EditText) findViewById(R.id.input_password);
mContext = RegisterActivity.this;
mProgressBar.setVisibility(View.GONE);
loadingPleaseWait.setVisibility(View.GONE);
}
private boolean isStringNull(String string){
Log.d(TAG, "isStringNull: checking string if null.");
if(string.equals("")){
return true;
}
else{
return false;
}
}
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 the username is not already in use
if(firebaseMethods.checkIfUsernameExists(username, dataSnapshot)){
append = myRef.push().getKey().substring(3,10);
Log.d(TAG, "onDataChange: username already exists. Appending random string to name: " + append);
}
username = username + append;
//add new user to the database
firebaseMethods.addNewUser(email, username, "", "", "");
Toast.makeText(mContext, "Signup successful. Sending verification 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);
}
}
}
Here are the firebase methods like to register new email,add new user, send verification email etc...
FirebaseMethods.java
public class FirebaseMethods {
private static final String TAG = "FirebaseMethods";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private String userID;
private Context mContext;
public FirebaseMethods(Context context) {
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mContext = context;
if(mAuth.getCurrentUser() != null){
userID = mAuth.getCurrentUser().getUid();
}
}
public boolean checkIfUsernameExists(String username, DataSnapshot datasnapshot){
Log.d(TAG, "checkIfUsernameExists: checking if " + username + " already exists.");
User user = new User();
for (DataSnapshot ds: datasnapshot.child(userID).getChildren()){
Log.d(TAG, "checkIfUsernameExists: datasnapshot: " + ds);
user.setUsername(ds.getValue(User.class).getUsername());
Log.d(TAG, "checkIfUsernameExists: username: " + user.getUsername());
if(StringManipulation.expandUsername(user.getUsername()).equals(username)){
Log.d(TAG, "checkIfUsernameExists: FOUND A MATCH: " + user.getUsername());
return true;
}
}
return false;
}
/**
* Register a new email and password to Firebase Authentication
* #param email
* #param password
* #param username
*/
public void registerNewEmail(final String email, String password, final String username){
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(mContext, R.string.auth_failed,Toast.LENGTH_SHORT).show();
}
else if(task.isSuccessful()){
//send verification email
sendVerificationEmail();
userID = mAuth.getCurrentUser().getUid();
Log.d(TAG, "onComplete: Authstate changed: " + userID);
}
}
});
}
public void sendVerificationEmail(){
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()){
}else{
Toast.makeText(mContext,"Couldn't send verification email.",Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void addNewUser(String email, String username, String description, String website, String profile_photo){
User user = new User( userID, 1, email, StringManipulation.condenseUsername(username) );
myRef.child(mContext.getString(R.string.dbname_users))
.child(userID)
.setValue(user);
UserAccountSettings settings = new UserAccountSettings(
description,
username,
0,
0,
0,
profile_photo,
username,
website
);
myRef.child(mContext.getString(R.string.dbname_user_account_settings))
.child(userID)
.setValue(settings);
}
}
This are the log lines....
01-09 13:16:06.014 21548-21548/com.example.vishal.myinstagram D/RegisterActivity: onAuthStateChanged:signed_out
01-09 13:16:06.015 21548-21588/com.example.vishal.myinstagram D/FA: Connected to remote service
01-09 13:16:06.015 21548-21588/com.example.vishal.myinstagram V/FA: Processing queued up service tasks: 4
01-09 13:16:06.017 21548-21994/com.example.vishal.myinstagram W/System: ClassLoader referenced unknown path: /data/data/com.google.android.gms/app_chimera/m/0000003a/n/arm64-v8a
01-09 13:16:11.043 21548-21588/com.example.vishal.myinstagram V/FA: Inactivity, disconnecting from the service
01-09 13:16:21.029 21548-21548/com.example.vishal.myinstagram W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
01-09 13:16:21.957 21548-21548/com.example.vishal.myinstagram W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
01-09 13:16:32.737 21548-21548/com.example.vishal.myinstagram D/RegisterActivity: checkInputs: checking inputs for null values.
01-09 13:16:32.743 21548-21548/com.example.vishal.myinstagram W/BiChannelGoogleApi: [FirebaseAuth: ] getGoogleApiForMethod() returned Gms
01-09 13:16:34.088 21548-21548/com.example.vishal.myinstagram D/FirebaseMethods: createUserWithEmail:onComplete:false
Thanks in advance...
So before you can set any OnClickListener on a view, you must first initialize a variable with findViewById(R.id.button_register). For example,
private Button registerButton;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
...
registerButton = (Button) findViewById(R.id.button_register);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click event
}
});
...
}
It is worth a mention that if you are using the support library >26 you do not need to cast the view anymore and can omit the (Button) in the initialization of registerButton. Android Studio should even prompt you that casting is no longer necessary.
https://stackoverflow.com/a/44903372/7900721
Now the R.id is something that is set upon the view in the layout XML file.
<Button
android:id="#+id/button_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/my_button_text"/>
Search for findViewById in the docs for more information
https://developer.android.com/reference/android/view/View.html
Just a recommendation for some cleaner code that is more readable, I'd recommend creating a private variable of View.OnClickListener that you pass in as the listener as shown below.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
fab.setOnClickListener(clickListener);
}
/**
* Handle click listeners
*/
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click event here
}
};
So if you begin to handle multiple click events, you could handle them in one section. As far as readability for others to maintain the code, it keeps methods such as onCreate() more concise with purpose of where each action is handled instead of scanning through multiple anonymous classes which would need to be instantiated for each setOnClickListener
My problem is solved...their was a problem in my jason file...anyway thanks everyone...

Categories