1

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

6
  • Hello. Just split the program execution (the execution of the onClickEvent handler) with IF condition: if (loggedIn) { startActivity (B) } else { startActivity(loginActivity) }
    – Klemikaze
    Apr 19, 2021 at 10:51
  • Can you share the code you already have? What kind of authentication are you using?
    – jonas
    Apr 19, 2021 at 10:51
  • @jonas I am still working on the Login Activity screen, but I have both Activity A and B created. The Login uses firebase authentication. So is there any code that I can use to direct the user on the condition of whether logged In or not when a button is clicked on any activity on my app? Apr 19, 2021 at 10:55
  • if you use firebase authentication you can take this: stackoverflow.com/questions/37873608/… code !
    – jonas
    Apr 19, 2021 at 11:04
  • Can I ask what happens when the button is pressed and user is logged in?
    – LCZ
    Apr 19, 2021 at 11:16

1 Answer 1

0

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;

6
  • I have added the code of my LoginActivity to the question can you check to see if this solution can be implemented in regards to your answer ' assuming loggedIn is the boolean variable storing whether the user was logged in"....... Apr 19, 2021 at 11:17
  • Your code seems ok. The app starts on Login activity, then if the user is already logged in, he/she is redirected to the Main1 activity.
    – LCZ
    Apr 19, 2021 at 11:20
  • Yes, but here is what I really want, I want to create a new activity on that activity it will contain a button, if user is not logged in I want it to come to this LoginActivity, but if the user is logged in when that button is clicked it should open another activity. My goal is to ensure that the new activity I am creating only those that are logged in can access Apr 19, 2021 at 11:33
  • I have added how to implement the new activity, is it ok?
    – LCZ
    Apr 19, 2021 at 11:39
  • I don't know why but I still encountered some issues in the code during my final implementation, what to do if it says Cannot resolve symbol 'loggedIn' on the Activity class where i added the code Apr 19, 2021 at 20:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.