I have created a signup form linked with Firebase. Onclick Signup button generated an unique id which I have later stored in
String str = userid;
But now I want to pass this String str value back into my main activity so that I can get that unique id and can later on use in my other code.
I have tried many methods like bundle and passing string through intent but I'm getting nothing. Please help me resolving this issue.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignIn = (Button) findViewById(R.id.sign_in_button);
btnSignUp = (Button) findViewById(R.id.sign_up_button);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputNumber = (EditText) findViewById(R.id.number);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnResetPassword = (Button) findViewById(R.id.btn_reset_password);
btnResetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(SignupActivity.this, ResetPasswordActivity.class));
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rootNode = FirebaseDatabase.getInstance();
reference = rootNode.getReference("users");
final String userid = reference.push().getKey();
final String name = inputName.getText().toString().trim();
final String email = inputEmail.getText().toString().trim();
final String Number = inputNumber.getText().toString().trim();
final String password = inputPassword.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(getApplicationContext(), "Enter your name!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(Number)) {
Toast.makeText(getApplicationContext(), "Enter mobile number!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "Password too short, enter minimum 6 characters!", Toast.LENGTH_SHORT).show();
return;
}
final UserHelperClass helperClass = new UserHelperClass(name, email,Number,password,userid);
progressBar.setVisibility(View.VISIBLE);
//create user
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// 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(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
String str = userid;
reference.child(userid).setValue(helperClass);
startActivity(new Intent(SignupActivity.this, Home.class));
finish();
}
}
});
}
});
}
You can use SharedPreferences API to save this string to an XML file in the second activity and read it from the same XML file in the MainActivity.
To save the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("key", userid);
editor.apply();
To retrieve the string:
SharedPreferences sharedPreferences = getSharedPreferences("shared_pref", 0);
String userid = sharePreferences.getString("key", "NOT FOUND");
You can read more about SharedPreferences here
You can start your second activity saying startActivityForResult
(See here), this way you can pass strings, numbers... back to the MainActivity from where you started your second activity once your second activity finishes.
Like
First Activity:
Intent i = new Intent(getApplicationContext(), yourSecondActivity.class);
i.putExtra("name", "value");
startActivityForResult(i, requestCode);
Second activiy:
Intent output = new Intent();
output.putExtra("name", "value");
setResult(RESULT_OK, output);
finish();
To recieve output in first Activity
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
String value = data.getStringExtra("name");
Related
first i'm sorry of my bad english , i have a problem with my code , when i want to query and check if the user that sign in is in the database or not , and also check of his password and if he tourist or tour guide and when i debug the program , the first statement is passed and the second which is check of the password , he never passed and start the next page , it say that the password is wrong , how i fix this problem pleass :(
TextView show7, signup_btn_label;
ImageButton imagebuttonn1;
EditText tourg_email_address, tourg_password;
Button btnn_login;
private FirebaseAuth mAuth1;
private DatabaseReference jLoginDatabase;
private FirebaseDatabase fDatabase;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logintourguide);
//initialise mProgressDialog
mProgressDialog = new ProgressDialog(Logintourguide.this);
show7 = (TextView) findViewById(R.id.forgot_password);
show7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), Forgetpassword.class);
startActivity(i);
}
});
imagebuttonn1 = findViewById(R.id.imagebuttonn);
imagebuttonn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
signup_btn_label = (TextView) findViewById(R.id.signup_btn_label);
signup_btn_label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), activity_signup_tourguide.class);
startActivity(i);
}
});
tourg_email_address = (EditText) findViewById(R.id.tourg_email_address);
tourg_password = (EditText) findViewById(R.id.tourg_password);
btnn_login = (Button) findViewById(R.id.btnn_login);
mAuth1 = FirebaseAuth.getInstance();
btnn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
final String email = tourg_email_address.getText().toString().trim();
final String pass = tourg_password.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
Toast.makeText(Logintourguide.this, "Please enter your email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(pass)) {
Toast.makeText(Logintourguide.this, "Please enter your password", Toast.LENGTH_LONG).show();
return;
}
if (tourg_password.length() < 8) {
Toast.makeText(Logintourguide.this, "password must be 8 or long", Toast.LENGTH_LONG).show();
return;
}
if (!email.matches(emailPattern)) {
Toast.makeText(Logintourguide.this, "invalid email address", Toast.LENGTH_LONG).show();
return;
}
//show dialog
mProgressDialog.show();
//set content view
mProgressDialog.setContentView(R.layout.progress_dialog);
//set transparent background
mProgressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
///FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
// DatabaseReference rootRef = FirebaseDatabase.getInstance()
final DatabaseReference uidRef = FirebaseDatabase.getInstance().getReference("Users");
final Query checkUser = uidRef.orderByChild("email").equalTo(email);
checkUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (pass.equals(dataSnapshot.child("password").getValue())) {
if (dataSnapshot.child("sign up as").getValue().equals("Tour Guide")) {
String passwordfromDB = (String) dataSnapshot.child("password").getValue(String.class);
String emailfromDB = (String) dataSnapshot.child("email").getValue(String.class);
String fullNamefromDB = (String) dataSnapshot.child("fullName").getValue(String.class);
String phoneNumberfromDB = (String) dataSnapshot.child("phoneNumber").getValue(String.class);
//put it iin that intent so we can pass it to tourguide class
Intent intent = new Intent(getApplicationContext(), TourGuide_Profile.class);
intent.putExtra("full name", fullNamefromDB);
intent.putExtra("email", emailfromDB);
intent.putExtra("phone No", phoneNumberfromDB);
intent.putExtra("password", passwordfromDB);
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "welcome back tour guide!",
Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "Sorry ! You are not authorized to access this application!",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "wrong password",
Toast.LENGTH_SHORT).show();
}
} else {
mProgressDialog.dismiss();
Toast.makeText(Logintourguide.this, "no such user exist !",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("Tag", databaseError.getMessage());
}
});
// uidRef.addListenerForSingleValueEvent(valueEventListener);
// checkUser.addListenerForSingleValueEvent(valueEventListener);
}
});
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm making a shopping App and I've almost finished the App. But I wanted to add the Forget password feature after all. I could've done it using FirebaseAuth but for registration and login, I haven't used FirebaseAuth.
My user details are going straight to the firebase database and are being saved in the Users table. Since I'm new to android app developing I don't know how to implement my app with forget password feature.
This is my database structure :
This is my RegisterActivity:
public class RegisterActivity extends AppCompatActivity {
private Button CreateAccountButton;
private EditText InputUsername, InputPhoneNumber, InputPassword, InputRePassword, InputEmail, InputName;
private ProgressDialog loadingBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
CreateAccountButton = (Button) findViewById(R.id.register_btn);
InputUsername = (EditText) findViewById(R.id.register_username);
InputPhoneNumber = (EditText) findViewById(R.id.register_Number);
InputPassword = (EditText) findViewById(R.id.register_password);
InputRePassword = (EditText) findViewById(R.id.register_repassword);
InputEmail = (EditText) findViewById(R.id.register_email);
InputName = (EditText) findViewById(R.id.register_name);
loadingBar = new ProgressDialog(this);
CreateAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateAccount();
}
});
}
private void CreateAccount() {
String name = InputName.getText().toString();
String username = InputUsername.getText().toString();
String phone = InputPhoneNumber.getText().toString();
String password = InputPassword.getText().toString();
String repassword = InputRePassword.getText().toString();
String email = InputEmail.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(this, "Please enter your Name", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "Please enter your Username", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(phone)) {
Toast.makeText(this, "Please enter your Phone Number", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter your Password", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(repassword)) {
Toast.makeText(this, "Please re-enter your Password", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(email)) {
Toast.makeText(this, "Please enter your Email", Toast.LENGTH_SHORT).show();
} else {
loadingBar.setTitle("Creating Account");
loadingBar.setMessage("Please wait.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
ValidatephoneNumber(username, name, phone, password, repassword, email);
}
}
private void ValidatephoneNumber(final String username, final String name, final String phone, final String password, final String repassword, final String email)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(!(dataSnapshot.child("Users").child(username).exists()))
{
HashMap<String, Object> userdataMap = new HashMap<>();
userdataMap.put("username", username);
userdataMap.put("name", name);
userdataMap.put("phone", phone);
userdataMap.put("password", password);
userdataMap.put("email", email);
RootRef.child("Users").child(username).updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(RegisterActivity.this, "Your account has been created!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent);
}
else
{
loadingBar.dismiss();
Toast.makeText(RegisterActivity.this, "Connection Error. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
Toast.makeText(RegisterActivity.this,"This Username already exists! Try another Username", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
And here's my LoginActivity:
public class LoginActivity extends AppCompatActivity {
private EditText InputUsername, InputPassword;
private Button LoginButton;
private ProgressDialog loadingBar;
private String parentDbName = "Users";
private CheckBox chkBoxRememberMe;
private TextView AdminLink, UserLink, ForgetPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton = (Button) findViewById(R.id.main_login_btn);
InputUsername = (EditText) findViewById(R.id.login_username);
InputPassword = (EditText) findViewById(R.id.password);
AdminLink = (TextView) findViewById(R.id.adminPanel);
UserLink = (TextView) findViewById(R.id.userLogin);
loadingBar = new ProgressDialog(this);
chkBoxRememberMe = (CheckBox) findViewById(R.id.remember_me_chkb);
ForgetPassword = (TextView) findViewById(R.id.forgetPassword);
Paper.init(this);
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginUser();
}
});
AdminLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginButton.setText("Login Admin");
AdminLink.setVisibility(View.INVISIBLE);
UserLink.setVisibility(View.VISIBLE);
parentDbName = "Admins";
}
});
UserLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
LoginButton.setText("Login");
AdminLink.setVisibility(View.VISIBLE);
UserLink.setVisibility(View.INVISIBLE);
parentDbName = "Users";
}
});
ForgetPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ForgotPassowrdActivity.class));
}
});
}
private void LoginUser() {
String username = InputUsername.getText().toString();
String password = InputPassword.getText().toString();
if (TextUtils.isEmpty(username))
{
Toast.makeText(this, "Please enter your Username", Toast.LENGTH_SHORT).show();
}
else if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please enter your Password", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.setTitle("Logging in to the Account");
loadingBar.setMessage("Please wait.");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
AllowAccessToAccount(username, password);
}
}
private void AllowAccessToAccount(final String username, final String password)
{
if(chkBoxRememberMe.isChecked())
{
Paper.book().write(Prevelant.userUsernameKey, username);
Paper.book().write(Prevelant.userPasswordKey,password);
}
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.child(parentDbName).child(username).exists())
{
Users usersData = dataSnapshot.child(parentDbName).child(username).getValue(Users.class);
if(usersData.getUsername().equals(username))
{
if(usersData.getPassword().equals(password))
{
if(parentDbName.equals("Admins"))
{
Toast.makeText(LoginActivity.this, "Welcome Admin, You've logged in successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, AdminCategoryActivity.class);
startActivity(intent);
}
else if(parentDbName.equals("Users"))
{
Toast.makeText(LoginActivity.this, "Logged in successfully!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
Prevelant.currentOnlineUser = usersData;
startActivity(intent);
}
}
else
{
Toast.makeText(LoginActivity.this, "This Password is incorrect!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
else
{
Toast.makeText(LoginActivity.this, "This Username is not registered!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError)
{
}
});
}
}
Can I please know how to implement my code for forget password feature? I really appreciate your help!
This comes inbuilt with firebase:
FirebaseAuth.getInstance().sendPasswordResetEmail("user#example.com")
I make a modal to login, if username and password are correct another activity will open, but it always gives a wrong answer even i put a correct username and password.
This is my code :
public void Admin(View view){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.activity_login, null);
final EditText username = (EditText) mView.findViewById(R.id.txt_username);
final EditText password = (EditText) mView.findViewById(R.id.txt_password);
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
Button submit = (Button) mView.findViewById(R.id.btn_submit);
final AlertDialog dialog = mBuilder.create();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(user.equals("admin") && (pass.equals("admin"))){
try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Your Username and Password is wrong", Toast.LENGTH_SHORT).show();
}
}
});
mBuilder.setView(mView);
dialog.show();
}
Put the username and password variables inside the onClickedListener(). This will gonna fetch the current values of the variables. Declare it outside the Listener and put the implementation inside. Observe and try this code. This might help.
public class MainActivity extends Activity {
Button b1,b2;
EditText ed1,ed2;
TextView tx1;
int counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById(R.id.button);
ed1 = (EditText)findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
b2 = (Button)findViewById(R.id.button2);
tx1 = (TextView)findViewById(R.id.textView3);
tx1.setVisibility(View.GONE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ed1.getText().toString().equals("admin") &&
ed2.getText().toString().equals("admin")) {try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getApplicationContext(), "Wrong
Credentials",Toast.LENGTH_SHORT).show();
tx1.setVisibility(View.VISIBLE);
tx1.setBackgroundColor(Color.RED);
counter--;
tx1.setText(Integer.toString(counter));
if (counter == 0) {
b1.setEnabled(false);
}
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
}
You are assigning the user and password values before the submit button onClick event is called, therefore the values are always going to be empty. You can fix this by moving the following lines inside the onClick(View view) method:
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
This 2 line will return empty String
final String user = username.getText().toString().trim();
final String pass = password.getText().toString().trim();
Because you are getting text form EditText before user type anything.
What you actually need? You have to collect text from EditText after submit button click.
So Use thouse line inside OnCLickListener
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
user = username.getText().toString().trim();
pass = password.getText().toString().trim();
if(user.equals("admin") && (pass.equals("admin"))){
try{
Intent intent = new Intent(MainActivity.this,InputActivity.class);
startActivity(intent);
}catch (Exception e){
Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Your Username and Password is wrong", Toast.LENGTH_SHORT).show();
}
}
});
where I can put SharedPreference in my working progress thesis project. I'm having a simple trouble in here. here is my sample code for loginActivity im still wondering on how/where I put the other SharedPreference code.
Im having trouble with one time login using SharedPreference .I don't know where do i put the code. i searched thru the net but nothing works for me i know i am having trouble placing the code but i can't fix it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.prgBar);
btnLogin = findViewById(R.id.user_login);
userEmail = findViewById(R.id.user_email);
userPwd = findViewById(R.id.user_password);
btnReg = findViewById(R.id.user_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = userEmail.getText().toString();
final String password = userPwd.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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()) {
// there was an error
if (password.length() < 6) {
userPwd.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, userInterface.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Since you are using Firebase-authentication, you do not need to use SharedPreferences to see if the user had logged in before.
You can do this, example in the Splash Activity //first activity
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
if(user!=null){
//Signed in, go to home activity
Intent i=new Intent(SplashActivity.this,HomeActivity.class);
startActivity(i);
}
else{
//not logged in
Intent intent=new Intent(SplashActivity.this,LoginActivity.class);
startActivity(intent);
}
I make an sign up activity to create new user on Firebase using Simple Email Password shown below
CreateAccountActivity
public class CreateAccountActivity extends AppCompatActivity {
private ProgressDialog mprogress;
private RelativeLayout signUpactivity;
FirebaseUser user;
private Button msignUp;
public EditText mName,mEmail,mPassword,mCon_Password,mschl_name;
Spinner gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creat_acc);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
mprogress = new ProgressDialog(this);
msignUp = (Button) findViewById(R.id.signUp);
signUpactivity = (RelativeLayout) findViewById(R.id.activity_signUp);
mName = (EditText) findViewById(R.id.namefield);
mEmail = (EditText) findViewById(R.id.emailField);
mPassword = (EditText) findViewById(R.id.passwordField);
mschl_name = (EditText) findViewById(R.id.sname);
String[] option = new String[]{
"Male", "Female"
};
gender = (Spinner) findViewById(R.id.gender);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, option);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
gender.setAdapter(arrayAdapter);
msignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isNetworkAvailable()){
mprogress.setMessage("Creating Account...");
mprogress.show();
mprogress.setCanceledOnTouchOutside(false);
mprogress.setCancelable(false);
createAccount();
}else{
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
}
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
View focusview = null;
boolean cancel = false;
private void createAccount(){
final String name = mName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
final String gendertxt = gender.getSelectedItem().toString();
final String schl_name = mschl_name.getText().toString();
String edu_email = email+"#edutree.com";
if (isNetworkAvailable()){
mAuth.createUserWithEmailAndPassword(edu_email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(Task<AuthResult> task) {
if(task.isSuccessful()){
user = FirebaseAuth.getInstance().getCurrentUser();
String user_email = user.getEmail();
String gendertxt = gender.getSelectedItem().toString();
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder().setDisplayName(name).build();
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
}
});
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);
}else{
Snackbar.make(signUpactivity, "Error occurred" , Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
});
}else {
Snackbar.make(signUpactivity, "Network UnAvailable", Snackbar.LENGTH_SHORT).show();
mprogress.dismiss();
}
}
}
When user enters the information it start method CreateAccount() and then when task is successful it updates user profile and set the display name and Starts the MainActivity. but it starts the MainActivty its not showing the user name.
MainActivity
Can Anyone help me to fix this problem, and when user get sign out and sign in again then it shows the name otherwise it didn't show after Sign up.
Any Answers were highly appreciated
You need to move the code that starts MainActivity to inside the onComplete() method for the profile change. Right now your code starts the Firebase user profile change to store the display name, but it shows MainActivity before that user profile change is completed.
You can update this piece of your code, look at what I added at the end of the onComplete() method:
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(Task<Void> task) {
if(task.isSuccessful()){
Log.d("Profile", "User Profile Updated successfully");
FirebaseCrash.log("Profile Updated");
}else {
Log.d("Error","error while updating profile");
FirebaseCrash.log("Error while updating profile");
}
mprogress.dismiss();
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
});
Then, you can remove this code later in the function:
mprogress.dismiss();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(CreateAccountActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
Toast.makeText(CreateAccountActivity.this, "Welcome "+ FirebaseAuth.getInstance().getCurrentUser().getEmail(), Toast.LENGTH_LONG).show();
}
},500);