The app I'm working on prompts for the user to log in using Firebase when the app is opened. If the app is completely closed, then upon opening it will take the user to the login screen. However, many of the workers at the company where I work don't close the app, they just send it to the background. That's a problem, because if I delete their account, it doesn't kick them out instantly; it only kicks them out once they close the app.
To fix this, I essentially coded the home screen such that every time the page reloads-whether coming to the foreground, returning home from a different activity, or starting up the app again-it logs the user out in the background, then re-logs them in, at which point it checks the validity of their user account.
The end goal of this is that if the user still has a valid login, they will be unaffected, but if they have an invalid login, they'll get locked out even if they haven't fully shut down the app.
However, currently the app kicks the user back to the login screen even with a valid login already entered.
Code for the Main Activity (login screen):
package com.priceelectric.xriley.priceprefab;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
final SharedPreferences.Editor mEditor = prefs.edit();
mAuth = FirebaseAuth.getInstance();
FirebaseAuth.getInstance().signOut();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
Log.d("loginTag", "onAuthStateChanged:signed_in:" + user.getUid());
Context context = getApplicationContext();
final Intent returnHome = new Intent();
returnHome.setClass(context, Home_Screen.class);
startActivity(returnHome);
}
else{
Log.d("loginTag", "onAuthStateChanged:signed_out");
}
}
};
final EditText usernameTextBox = (EditText) findViewById(R.id.usernameTextBox);
final EditText passwordTextBox = (EditText) findViewById(R.id.passwordTextBox);
usernameTextBox.setText(prefs.getString("username", ""));
passwordTextBox.setText(prefs.getString("password", ""));
final Button login = (Button) findViewById(R.id.loginButton);
assert login != null;
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mEditor.putString("username", usernameTextBox.getText().toString());
mEditor.putString("password", passwordTextBox.getText().toString());
mEditor.commit();
prefs.getInt("thing", 0);
final String email = usernameTextBox.getText().toString();
final String password = passwordTextBox.getText().toString();
// FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
// final String uid = user.getUid();
// final SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
// final SharedPreferences.Editor mEditor = prefs.edit();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("loginTag", "signInWithEmail:onComplete:" + task.isSuccessful());
if(!task.isSuccessful()){
Log.w("loginTag", "signInWithEmail:failed", task.getException());
}
}
});
}
});
}
#Override
public void onStart(){
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop(){
super.onStop();
if(mAuthListener != null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
public void onBackPressed(){
Context context = getApplicationContext();
CharSequence notificationText = "You need to log in.";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, notificationText, duration).show();
}
}
Code for the home screen:
package com.priceelectric.xriley.priceprefab;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Home_Screen extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home__screen);
final Button paperworkButton = (Button) findViewById(R.id.paperworkButton);
mAuth = FirebaseAuth.getInstance();
final TextView versionLabel = (TextView) findViewById(R.id.versionLabel);
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
FirebaseAuth.getInstance().signOut();
mAuth.signInWithEmailAndPassword(prefs.getString("username", ""), prefs.getString("password", ""));
user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
//all good
}
else{
Context context = getApplicationContext();
CharSequence notificationText = "You need to log in.";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, notificationText, duration).show();
final Intent loginScreen = new Intent();
loginScreen.setClass(this, MainActivity.class);
startActivity(loginScreen);
}
if(prefs.getString("yourName", "").equals("")){
final Intent settingsScreen = new Intent();
settingsScreen.setClass(this, Settings_Screen.class);
startActivity(settingsScreen);
}
}
public void buttonOnClick(View view){
SharedPreferences prefs = getSharedPreferences("myDataStorage", MODE_PRIVATE);
switch(view.getId()){
case R.id.prefabOrderButton:
SharedPreferences.Editor mEditor = prefs.edit();
mEditor.putInt("itemNumberCounter", 0);
mEditor.commit();
final Intent prefabScreen = new Intent();
prefabScreen.setClass(this, Prefab_Order.class);
startActivity(prefabScreen);
break;
case R.id.safetyFormButton:
final Intent safetyReportScreen = new Intent();
safetyReportScreen.setClass(this, Safety_Report.class);
startActivity(safetyReportScreen);
break;
case R.id.resiPanelButton:
final Intent resiPanelScreen = new Intent();
resiPanelScreen.setClass(this, Resi_Panel_Builder.class);
startActivity(resiPanelScreen);
break;
case R.id.onlineResourcesButton:
final Intent onlineResourcesScreen = new Intent();
onlineResourcesScreen.setClass(this, Online_Resources.class);
startActivity(onlineResourcesScreen);
break;
case R.id.settingsButton:
final Intent settingsScreen = new Intent();
settingsScreen.setClass(this, Settings_Screen.class);
startActivity(settingsScreen);
break;
case R.id.paperworkButton:
final Intent paperworkScreen = new Intent();
paperworkScreen.setClass(this, Paperwork_Orders.class);
startActivity(paperworkScreen);
break;
}
}
#Override
public void onBackPressed(){
//do nothing
}
}
Suggestions would be appreciated.
In the Home_Screen activity, I think you would get better results if you added a completion listener to signInWithEmailAndPassword(), similar to what you have in your MainActivity.
With the existing code:
mAuth.signInWithEmailAndPassword(prefs.getString("username", ""), prefs.getString("password", ""));
user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null){
//all good
}
you are requesting the current user before the sign-in has completed, so user is null.
Add the completion listener and move the code to generate the toast and start MainActivity there, running it when task.isSuccessful() is false.
Also, instead of using sign-out/sign-in to test whether the user account is still valid, you might want to experiment with FirebaseUser.reload(). The documentation indicates it returns a failure result if the current user account is disabled or deleted.
Use a completion listener to get the reload() status:
user.reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
// account is still valid
} else {
// account is no longer valid
}
}
});
Related
I am new to coding, please I need help on this specific function I will be so grateful if anyone could help.
I am working on an android studio project, and on my activity (supposed Activity A) I want to place a button which when clicked it will open Supposed Activity B.
I have been able to setup onclick function and intent to open Activity B on button click.
But now what I want is if the user is not logged in then it should take the user to LoginActivity when that button is clicked, but when user is logged in it should take user direct to Activity B.
Please how can I achieve this on my Activity? Thanks in anticipation of a solution.
Below is my LoginActivity Code
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.sckoolboy.premiumapp.R;
public class Login extends AppCompatActivity {
EditText mEmail,mPassword;
Button mCreateBtn,mLoginBtn;
TextView forgotTextLink;
ProgressBar progressBar;
FirebaseAuth fAuth;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(Login.this, Main1.class));
finish();
}
setContentView(R.layout.activity_login);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.password);
progressBar = findViewById(R.id.progressBar);
fAuth = FirebaseAuth.getInstance();
mLoginBtn = findViewById(R.id.loginBtn);
mCreateBtn = findViewById(R.id.createText);
forgotTextLink = findViewById(R.id.forgotPassword);
mLoginBtn.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("PremiumKey is Required.");
return;
}
if(password.length() < 6){
mPassword.setError("PremiumKey not valid");
return;
}
progressBar.setVisibility(View.VISIBLE);
// authenticate the user
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Login.this, "Premium Successfully Unlocked", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),Main1.class));
}else {
Toast.makeText(Login.this, "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});
mCreateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Register.class));
}
});
forgotTextLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetMail = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter Your Email To Received Reset Link.");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String mail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(mail).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(Login.this, "Reset Link Sent To Your Email.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Login.this, "Error ! Reset Link is Not Sent" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close the dialog
}
});
passwordResetDialog.create().show();
}
});
}
}
using firebase authentication, how can i go about it from here
You can use an if block to switch between starting different activities, depending on whether the user was logged in or not.
For example, assuming loggedIn is the boolean variable storing whether the user was logged in, and button is the button,
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(v -> {
if (loggedIn) {
// Start ActivityB, user has logged in
Intent intent = new Intent(/* context here */, Main1.class);
startActivity(intent);
} else {
// Redirect to LoginActivity, user hasn't logged in
Intent intent = new Intent(/* context here */, Login.class);
startActivity(intent);
}
});
and the XML design for the new activity:
<!-- Root layout above..... -->
<Button
android:text="Log in"
android:id="#+id/button"/>
<!--Other elements below -->
You can get the login condition from Firebase's API, (reference made to https://stackoverflow.com/a/44585789/12204281), the method call should be:
FirebaseAuth.getInstance().getCurrentUser(), and this method returns null when user is not logged in.
So you can check if that value is null using equals operator and store it in loggedIn:
boolean loggedIn = FirebaseAuth.getInstance().getCurrentUser() != null;
This question already has answers here:
Activity has leaked window that was originally added
(48 answers)
Closed 2 years ago.
What is this error, and why does it happen?
E/WindowManager: android.view.WindowLeaked: Activity com.example.houseoffashion.MainActivity has leaked window DecorView#b273f3b[Already logged in] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:583)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:363)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:128)
at android.app.Dialog.show(Dialog.java:454)
at com.example.houseoffashion.MainActivity.onCreate(MainActivity.java:69)
at android.app.Activity.performCreate(Activity.java:7383)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:5477)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2000)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
I face this problem in two android projects. In one I was trying to retrieve data from Firebase into Recyclerview and in another, I was trying to login using phone number but in both cases, logcat is showing:
it does not display the home page. it just buffering on a login page tell me what happened and how can i solve that problem in accurate way.
The code is that...
package com.example.houseoffashion;
//import library
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.houseoffashion.Model.Users;
import com.example.houseoffashion.Prevalent.Prevalent;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import io.paperdb.Paper;
public class MainActivity extends AppCompatActivity {
private ProgressDialog LoadingBar;
private String parentDbName = "Users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//login Button
Button joinnowbutton = (Button) findViewById(R.id.btn2);
Button loginbutton = (Button) findViewById(R.id.btn1);
LoadingBar = new ProgressDialog(this);
Paper.init(this);
//when on click a login button
loginbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
});
//userid amd userpassword
String userPhoneKey = Paper.book().read(Prevalent.userPhoneKey);
String userPasswordKey = Paper.book().read(Prevalent.userPasswordKey);
//get id and password for login
if (userPhoneKey != "" && userPasswordKey != "")
{
if (!TextUtils.isEmpty(userPhoneKey) && !TextUtils.isEmpty(userPasswordKey))
{
AllowAccess(userPhoneKey, userPasswordKey);
//progress dialogbar
LoadingBar.setTitle("Already logged in");
LoadingBar.setMessage("Please wait ........");
LoadingBar.setCanceledOnTouchOutside(false);
LoadingBar.show();
}
}
}
private void AllowAccess(final String phone_number, final String password)
{
final DatabaseReference RootRef;
RootRef = FirebaseDatabase.getInstance().getReference();
//store data in firebase realtime data
RootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
if(dataSnapshot.child(parentDbName).child(phone_number).exists())
{
Users usersData = dataSnapshot.child(parentDbName).child(phone_number).getValue(Users.class);
if (usersData.getPhone_number().equals(phone_number))
{
if (usersData.getPassword().equals(password))
{
//display a msg already logged in
Toast.makeText(MainActivity.this, "Please Wait! You have already logged in...", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
Prevalent.currentOnlineUser = usersData;
startActivity(intent);
}
else
{
//dismiss a bar and set a msg incorrect password
LoadingBar.dismiss();
Toast.makeText(MainActivity.this, "incorrect password...", Toast.LENGTH_SHORT).show();
}
}
}
else
{
//after successfully login go to the home activity
Toast.makeText(MainActivity.this, "Account with this" + phone_number + "number do not exists.", Toast.LENGTH_SHORT).show();
LoadingBar.dismiss();
}
}
}
}
Possible duplicate of Activity has leaked window that was originally added
You should give a look to that question. It is very useful.
I'm using firebase and google sign in. The problem is that when I click on the sign in button, it log in automatically even without any google account registered in firebase auth users! Also the "choose account" dialog doesn't appear when user isn't in firebase auth users and when it is. I would like to show this dialog.
LoginActivity
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.example.schooltest.ResetPasswordActivity;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
//check the current user
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.et_email_address);
inputPassword = (EditText) findViewById(R.id.et_password);
final Button ahlogin = (Button) findViewById(R.id.login_btn);
progressBar = (ProgressBar) findViewById(R.id.loading_spinner);
TextView btnForgot = findViewById(R.id.forgot);
TextView btnSignUp = (TextView) findViewById(R.id.signup_here_Button);
button = (GoogleSignInButton) findViewById(R.id.login_google_btn);
mViewHelper = findViewById(R.id.view_helper);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, SignupActivity.class));
}
});
btnForgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
mAuth = FirebaseAuth.getInstance();
// Checking the email id and password is Empty
ahlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Email is required.", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter Password", Toast.LENGTH_SHORT).show();
return;
}
if(password.length() < 6) {
inputPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
ahlogin.setVisibility(View.INVISIBLE);
//authenticate user
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
ahlogin.setVisibility(View.VISIBLE);
if (task.isSuccessful()) {
// there was an error
Log.d(TAG, "signInWithEmail:success");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
} else {
Log.d(TAG, "singInWithEmail:Fail");
Toast.makeText(LoginActivity.this, getString(R.string.failed), Toast.LENGTH_LONG).show();
}
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.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");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(LoginActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
SignUpActivity
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.example.schooltest.MainActivity;
import com.example.schooltest.R;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.shobhitpuri.custombuttons.GoogleSignInButton;
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String name = mName.getText().toString().trim();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("430102477506-gsgi3mjgd1bie5ml5nf316no2ki3llvj.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
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) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.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");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
Main Activity
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.example.schooltest.login.LoginActivity;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private String mName;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
View decorView = getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ClassFragment()).commit();
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Sets default values only once, first time this is called. The third
// argument is a boolean that indicates whether the default values
// should be set more than once. When false, the system sets the default
// values only the first time it is called.
PreferenceManager.setDefaultValues(this,
R.xml.pref_students, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_information, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_security, false);
PreferenceManager.setDefaultValues(this,
R.xml.pref_notifications, false);
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(MainActivity.this, FullscreenActivity.class);
startActivity(startIntent);
finish();
}
/**
* Inflates the menu, and adds items to the action bar if it is present.
*
* #param menu Menu to inflate.
* #return Returns true if the menu inflated.
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/**
* Handles app bar item clicks.
* Don't forget to add intent to addstudent
* #param item Item clicked.
* #return True if one of the defined items was clicked.
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_addStudent:
displayToast(getString(R.string.action_addStudent_message));
return true;
case R.id.action_settings:
Intent settingsIntent = new Intent(this,
SettingsActivity.class);
startActivity(settingsIntent);
return true;
case R.id.menu_logout_btn:
FirebaseAuth.getInstance().signOut();
sendToStart();
return true;
default:
// Do nothing
}
return super.onOptionsItemSelected(item);
}
/**
* Displays a Toast with the message.
*
* #param message Message to display
*/
public void displayToast(String message) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT).show();
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.navigation_class:
selectedFragment = new ClassFragment();
break;
case R.id.navigation_due:
selectedFragment = new DueFragment();
break;
case R.id.navigation_messages:
selectedFragment = new MessagesFragment();
break;
case R.id.navigation_class_updates:
selectedFragment = new ClassUpdatesFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
return true;
}
};
}
I am trying to implement the logout method in my android application
and write the below code. Main Activity is a login activity and ChoosingProcActivity is an activity which contains logout button.
when I press logout button it moves me to Main Activity but when I open application next time it directly moves me to ChoosingProcActivity.
in addition to that when I log in successfully and then go back or press back it show Main Activity (login). how can I avoid this?
are shared preferences wrong?
Main Activity code
package com.example.lenovo.tactic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
EditText email_input,password_input;
TextView reset;
Button btnLogin;
Boolean isLogedBefore = false;
Vibrator v;
String organizer_ID;
SharedPreferences test_name;
final String loginURL = "http://tactickevent.com/phpApp/loginApp.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email_input = findViewById(R.id.etUserName);
password_input = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
test_name.getString("email", "");
test_name.getString("organizer_ID", "");
// if(isLogedBefore == true){
boolean is = test_name.getBoolean("isLoged", false);
if (is==true) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
// }
}
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
validateUserData();
}
});
}
private void validateUserData() {
//first getting the values
final String email = email_input.getText().toString();
final String password = password_input.getText().toString();
//checking if email is empty
if (TextUtils.isEmpty(email)) {
email_input.setError("أدخل البريد الالكتروني من فضلك");
email_input.requestFocus();
// Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//checking if password is empty
if (TextUtils.isEmpty(password)) {
password_input.setError("أدخل كلمة السر من فضلك");
password_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//validating email
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
email_input.setError("أدخل بريد الكتروني صحيح");
email_input.requestFocus();
//Vibrate for 100 milliseconds
v.vibrate(100);
btnLogin.setEnabled(true);
return;
}
//Login User if everything is fine
//first getting the values
//String emaill = email_input.getText().toString();
// String passwordd = password_input.getText().toString();
loginUser(email,password);
}
private void loginUser(final String email,final String password) {
RequestQueue queue = Volley.newRequestQueue(this);
//Call our volley library
StringRequest stringRequest = new StringRequest(Request.Method.POST,loginURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
// Toast.makeText(getApplicationContext(),response.toString(), Toast.LENGTH_SHORT).show();
JSONObject obj = new JSONObject(response);
if (obj.getInt("value")== 1) {
organizer_ID = obj.getString("organizer_ID");
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeID(organizer_ID);
//starting the ChoosingProcActivity
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", organizer_ID);
//apply
editor.commit();
Toast.makeText(getApplicationContext(), "تم تسجيل الدخول بنجاح", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
// startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
} else{
Toast.makeText(getApplicationContext(),"هناك خطأ في كلمة السر أو البريد الالكتروني ", Toast.LENGTH_SHORT).show();
//getting user name
//Toast.makeText(getApplicationContext(), obj.getString("messagee"), Toast.LENGTH_SHORT).show();
//storing the user in shared preferences
//SharedPref.getInstance(getApplicationContext()).storeUserName(organizer_ID);
//starting the profile activity
//finish();
//startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Connection Error"+error, Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
}) {
//email key mean the value that will send to php in $_POST["email"];
//password key mean the value that will send to php in $_POST["password"];
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
queue.add(stringRequest);
/*
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, email, password);
try {
JSONObject jsonObject = new JSONObject(result1);
SharedPreferences.Editor editor = test_name.edit();
editor.putBoolean("isLoged",true);
editor.putString("email", email);
editor.putString("organizer_ID", jsonObject.getString("organizer_ID"));
//apply
editor.commit();
*/
}
}
code of second activity
package com.example.lenovo.tactic;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingProcActivity extends AppCompatActivity {
Button eventBTN, subeventBTN;
SharedPreferences test_name;
String emailToPass,organizer_ID;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing_proc);
eventBTN= (Button)findViewById(R.id.BtnEvent);
subeventBTN= (Button)findViewById(R.id.BtnSubEvent);
test_name = getSharedPreferences("NAME", Context.MODE_PRIVATE);
emailToPass= test_name.getString("email", "");
organizer_ID= test_name.getString("organizer_ID", "");
eventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, EventProcActivity.class);
startActivity(intent);
}
});
subeventBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ChoosingProcActivity.this, SubeventProcActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if(item.getItemId() ==R.id.logout)
{
preferences =getSharedPreferences("Name",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
finish();
}
return true;
}
}
You can finish your activity every time the test is true so that it can no longer be accessible from the stack.
boolean is = test_name.getBoolean("isLoged", false);
if (is) {
Intent intent = new Intent(MainActivity.this, ChoosingProcActivity.class);
startActivity(intent);
finish();
}
I am assuming that your MainActivity is the first one to get launched when opening the app.
In your MainActivity add this:
#Override
protected void onStart() {
super.onStart();
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, ChoosingProcActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
What it does during startup of your app it will query if there is someone already logged in if yes it will go to the ChoosingProcActivity. I am assuming that in your SharedPrefManager implementation you have a code to know if there is a logged in user.
In your login method uncomment the finish() method
startActivity(new Intent(getApplicationContext(), ChoosingProcActivity.class));
//finish();
After successfull login, if you press back button you will not see the MainActivity.
In your ChoosingProcActivity it will look like this:
#Override
protected void onStart() {
super.onStart();
if (!SharedPrefManager.getInstance(this).isLoggedIn()) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Basically, it will ask if there is currently logged in user if not, it will go back to the MainActivity.
EDIT In Logout you may use this as basis from your code,
logoutComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPrefManager.getInstance(getActivity()).clear();
Intent intent = new Intent(ChooseProcActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
});
I am creating user sign up application with parse. when I fill edit field and press signup button a toast message show that invalid token session.I have filled all filed.How can i resolve this problem.Here below is my code
package com.example.home.communicate
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignupActivity extends AppCompatActivity {
EditText editusername, editpassword, editemail, editrepassword;
Button signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editusername = (EditText) findViewById(R.id.usernamesignup);
editemail = (EditText) findViewById(R.id.email);
editpassword = (EditText) findViewById(R.id.passwordinsignup);
editrepassword = (EditText) findViewById(R.id.re_enterpassword);
signup = (Button) findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userSignUp();
}
});
}
private void userSignUp() {
String username = editusername.getText().toString().trim();
String email = editemail.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String repassword = editrepassword.getText().toString().trim();
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder(getString(R.string.error_intro));
if (username.length() == 0) {
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_username));
}
if (password.length()== 0){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_password));
}
if(!password.equals(repassword)){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_mismatched_passwords));
}
if (email.length()== 0){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_email));
}
if(validationError){
Toast.makeText(SignupActivity.this, validationErrorMessage.toString(),Toast.LENGTH_SHORT).show();
}
ParseUser user = new ParseUser();
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e==null){
Intent intent = new Intent(SignupActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
Toast.makeText(SignupActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
}
This could potentially happen when your current user is not completely logged out. Make sure to do a check on your current user and logout before signing up a new user.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
ParseUser.logOut();
}