user6866656
user6866656

Reputation:

Back button not working properly - Android

When I press the back button in my phone this activity is restarted instead of leaving the application.(This is the activity displayed when the user opens the app)

Here is the code, it is just a simple login activity, nothing different.

public class LoginActivity extends AppCompatActivity {

    public static final int RC_SIGN_IN = 1;
    private GoogleApiClient mGoogleApiClient;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    public static final String TAG = "MAIN_ACTIVITY";
    private String email, password;

    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    @BindView(R.id.google_button)
    SignInButton mGoogleBtn;

    @BindView(R.id.register_button)
    TextView mRegisterBtn;


    @BindView(R.id.email_edit_text)
    EditText mEmail;

    @BindView(R.id.password_edit_text)
    EditText mPassword;

    @BindView(R.id.login_button)
    ImageButton mLogin;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        ButterKnife.bind(this);

        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                if (firebaseAuth.getCurrentUser() != null) {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                }
            }
        };

        if (mAuth.getCurrentUser() != null) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

                        Toast.makeText(LoginActivity.this, R.string.connection_failed, Toast.LENGTH_LONG).show();

                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();


    }

    @OnClick(R.id.register_button)
    public void register() {
        startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
    }

    @OnClick(R.id.google_button)
    public void loginUsingGoogle() {
        signIn();
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    private void signIn() {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = result.getSignInAccount();
                firebaseAuthWithGoogle(account);
            } else {
                // Google Sign In failed, update UI appropriately
                // ...
            }
        }
    }

    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());

        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        Log.d(TAG, "signInWithCredential: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()) {
                            Log.w(TAG, "signInWithCredential", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }
                        // ...
                    }
                });
    }

    @OnClick(R.id.login_button)
    public void login() {
        email = mEmail.getText().toString();
        password = mPassword.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;
        }

        progressBar.setVisibility(View.VISIBLE);

        //authenticate user
        mAuth.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.
                        progressBar.setVisibility(View.GONE);
                        if (!task.isSuccessful()) {
                            // there was an error
                            if (password.length() < 6) {
                                mPassword.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, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                });
    }
}

I already tried this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    moveTaskToBack(true);
}

this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    finish();
}

and this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    System.exit(0);
}

Here's the log

java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
com.intellij.openapi.extensions.impl.PicoPluginExtensionInitializationException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:96)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getExtension(ExtensionComponentAdapter.java:119)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapters(ExtensionPointImpl.java:249)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.getExtensions(ExtensionPointImpl.java:194)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:100)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:87)
    at com.intellij.openapi.extensions.ExtensionPointName.getExtensions(ExtensionPointName.java:49)
    at com.intellij.tasks.TaskRepositoryType.getRepositoryTypes(TaskRepositoryType.java:40)
    at com.intellij.tasks.impl.TaskManagerImpl.loadRepositories(TaskManagerImpl.java:618)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:612)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:78)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistentComponent(ComponentStoreImpl.kt:291)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:520)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:123)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:107)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:90)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:282)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:231)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.access$300(ProjectManagerImpl.java:68)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:531)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:527)
    at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:198)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$8.run(CoreProgressManager.java:357)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.application.impl.ApplicationImpl$13$1.run(ApplicationImpl.java:633)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:160)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentImplementation(ExtensionComponentAdapter.java:66)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:73)
    ... 37 more
Caused by: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:157)
    ... 39 more
Caused by:

java.lang.RuntimeException: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:160)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentImplementation(ExtensionComponentAdapter.java:66)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getComponentInstance(ExtensionComponentAdapter.java:73)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.getExtension(ExtensionComponentAdapter.java:119)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapters(ExtensionPointImpl.java:249)
    at com.intellij.openapi.extensions.impl.ExtensionPointImpl.getExtensions(ExtensionPointImpl.java:194)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:100)
    at com.intellij.openapi.extensions.Extensions.getExtensions(Extensions.java:87)
    at com.intellij.openapi.extensions.ExtensionPointName.getExtensions(ExtensionPointName.java:49)
    at com.intellij.tasks.TaskRepositoryType.getRepositoryTypes(TaskRepositoryType.java:40)
    at com.intellij.tasks.impl.TaskManagerImpl.loadRepositories(TaskManagerImpl.java:618)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:612)
    at com.intellij.tasks.impl.TaskManagerImpl.loadState(TaskManagerImpl.java:78)
    at com.intellij.configurationStore.ComponentStoreImpl.initPersistentComponent(ComponentStoreImpl.kt:291)
    at com.intellij.configurationStore.ComponentStoreImpl.initComponent(ComponentStoreImpl.kt:96)
    at com.intellij.openapi.components.impl.PlatformComponentManagerImpl.initializeComponent(PlatformComponentManagerImpl.java:54)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:520)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:123)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:107)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:90)
    at com.intellij.openapi.project.impl.ProjectImpl.init(ProjectImpl.java:282)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.initProject(ProjectManagerImpl.java:231)
    at com.intellij.openapi.project.impl.ProjectManagerImpl.access$300(ProjectManagerImpl.java:68)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:531)
    at com.intellij.openapi.project.impl.ProjectManagerImpl$8.compute(ProjectManagerImpl.java:527)
    at com.intellij.openapi.progress.impl.CoreProgressManager$4.run(CoreProgressManager.java:198)
    at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
    at com.intellij.openapi.progress.impl.CoreProgressManager$8.run(CoreProgressManager.java:357)
    at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
    at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
    at com.intellij.openapi.application.impl.ApplicationImpl$13$1.run(ApplicationImpl.java:633)
    at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.bitbucket.connectors.jetbrains.tasks.BitbucketIssueRepositoryType PluginClassLoader[org.bitbucket.connector, 1.2.3-SNAPSHOT]
    at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:64)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.loadImplementationClass(ExtensionComponentAdapter.java:157)
    ... 39 more

Upvotes: 1

Views: 822

Answers (3)

Micha
Micha

Reputation: 394

The only reason I could think of why the system would restart an Activity would be because it crashed. Please check logcat, and maybe add it to the question.

Upvotes: 1

Gabi
Gabi

Reputation: 667

Add this intent in onBackPressed to close the app :

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            intent.putExtra("EXIT", true);

            startActivity(intent);

Upvotes: 0

Kenny Gunderman
Kenny Gunderman

Reputation: 500

Try to remove the onBackPressed() method from your code and clean your project

Upvotes: 0

Related Questions