0

I'm just learning to create android apps. I created two different apps, one for login using email and google using firebase and one to upload images into firebase storage. Both of these work individually. Now I'm trying to combine them. I've made the login part as SignUpActivity which when the user runs and logs-in successfully, should start the main activity, and go to my upload images part of the code, which I've coded under MainActivity.

I've tried various methods to execute this but I can't seem to get the intent part right. Additionally I can't seem to make the signupactivity the first activity. I've tried to go to app and editing the configuration to make signupactivity as my starting activity. but that crashes the app.

code flow: sign-up/login -> upload i.e SignUpActivity -> MainActivity

SignUpActivity (part of it)

public class SignUpActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    GoogleSignInClient mGoogleSignInClient;

    private FirebaseAuth mAuth;
    private String result;
    private Object MainActivity;

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

        findViewById(R.id.sign_in_button).setOnClickListener(this);
        findViewById(R.id.signOutButton).setOnClickListener(this);


        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                // for the requestIdToken, use getString(R.string.default_web_client_id), this is in the values.xml file that
                // is generated from your google-services.json file (data from your firebase project), uses the google-sign-in method
                // web api key
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();

        // Build a GoogleSignInClient with the options specified by gso.
        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

        // Set the dimensions of the sign-in button.
        SignInButton signInButton = findViewById(R.id.sign_in_button);
        signInButton.setSize(SignInButton.SIZE_WIDE);

        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        



    }

    private void updateUI(boolean signedIn) {
        if (signedIn) {
            findViewById(R.id.sign_in_button).setVisibility(View.GONE);
            Intent signInToMain = new Intent("my.app.master.MainActivity");
            startActivity(signInToMain);
        } else {
            findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);

        }
    }


    @Override
    public void onStart() {
        super.onStart();

        // Check if the user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();

        if (currentUser != null) {
            Log.d(TAG, "Currently Signed in: " + currentUser.getEmail());
            Toast.makeText(SignUpActivity.this, "Currently Logged in: " + currentUser.getEmail(), Toast.LENGTH_LONG).show();
        }
    }

    @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);
                Toast.makeText(this, "Google Sign in Succeeded",  Toast.LENGTH_LONG).show();
                firebaseAuthWithGoogle(account);
            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
                Toast.makeText(this, "Google Sign in Failed " + e,  Toast.LENGTH_LONG).show();
            }
        }

        if (requestCode == 1234) {

            // Successfully signed in
            if (resultCode == RESULT_OK) {
                // Successfully signed in
                FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                Toast.makeText(getApplicationContext(), "Successfully signed in", Toast.LENGTH_SHORT).show();


            }


        } else {
            // Sign in failed. If response is null the user canceled the sign-in flow using the back button. Otherwise check
            // response.getError().getErrorCode() and handle the error.
            // ...
            Toast.makeText(getApplicationContext(), "Unabled to Sign in", Toast.LENGTH_SHORT).show();
        }
    }


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

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.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
                            FirebaseUser user = mAuth.getCurrentUser();
                            Log.d(TAG, "signInWithCredential:success: currentUser: " + user.getEmail());
                            Toast.makeText(SignUpActivity.this, "Firebase Authentication Succeeded ",  Toast.LENGTH_LONG).show();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Toast.makeText(SignUpActivity.this, "Firebase Authentication failed:" + task.getException(),  Toast.LENGTH_LONG).show();
                        }
                    }
                });
    }

    public void signInToGoogle(){
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }



    
}

Manifest


      <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".SignUpActivity"></activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ImagesActivity"></activity>
    </application>

P.S: I know there are unnecessary parts of the code to implement something simple. but I've just started coding on an android studio and am still learning.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Have your tried doing: `Intent signInToMain = new Intent(this, MainActivity.class); startActivity(signInToMain);` – Prashant Jha Jul 06 '20 at 09:45
  • yes I've tried that. I used a modified version of if(username.getText().toString().equals("admin") && password.getText().toString().equals("admin")){ Toast.makeText(getApplicationContext(), "Redirecting...", Toast.LENGTH_SHORT).show(); Intent i = new Intent(login.this, your_new_activity_name.class); startActivity(i); } But I can't seem to get the Login Page to appear in the first place. I even changed the MainActivity to signUpActivity on my manifest. this makes my app crash. –  Jul 06 '20 at 10:06
  • Is it giving some kind of error? – Prashant Jha Jul 06 '20 at 10:07
  • If you encounter problems, it's best to create a [MCVE](https://stackoverflow.com/help/mcve) when posting a question. You posted **almost 400 lines of code** for this issue. That's a lot for people to parse and try to debug online. Please edit your question and isolate the problem, in that way you increase your chances of being helped. – Alex Mamo Jul 06 '20 at 10:08
  • it won't let me make signin activity my default activity. I've tried changing it in the manifest file but it crashes the app. I already checked and ran the signin part before i coded in the upload part. there seem to be no errors otherwise in the whole code. –  Jul 06 '20 at 10:24
  • It's very difficult to debug a crash without a stack trace. See [Unfortunately MyApp has stopped. How can I solve this?](/q/23353173) for Android-specific advice, and [What is a stack trace, and how can I use it to debug my application errors?](/q/3988788) for advice on what to do once you have the stack trace. If you still need help, edit your question to include the **complete stack trace**, as well as **which line of your code** the stack trace points to. – Ryan M Jul 09 '20 at 08:18

1 Answers1

0

just add

Intent signInToMain = new Intent("my.app.master.MainActivity");
startActivity(signInToMain);

inside "firebaseAuthWithGoogle" method above Toast you're printing of "Firebase Authentication Succeeded ".

Harsh Suvagiya
  • 106
  • 1
  • 3