App crashes after calling startActivity()

Viewed 617

i have an activity with registration (RegisterActivity) and after pressing register button i have to load another activity (MenuActivity) containing many fragments. The problem is when i click registration button that my app crush. How can i do this? Are there errors in my code? If necessary i'll post also .xml file of MenuActivity and MenuFragment. Thanks in advance to everyone! This is my code:

MenuActivity.class

public class MenuActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawer;

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

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
                R.string.navigation_drawer_open, R.string.navigation_drawer_close);

        drawer.addDrawerListener(toggle);
        toggle.syncState();

        if(savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new MenuFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_profile);
        }
    }

    @Override
    public void onBackPressed() {
        if(drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch(item.getItemId()) {

            case R.id.nav_menu:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new MenuFragment()).commit();
                break;
            case R.id.nav_profile:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ProfileFragment()).commit();
                break;
            case R.id.nav_send:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new SendFragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new SettingsFragment()).commit();
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

RegisterActivity.class

mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()) {
                            Toast.makeText(RegisterActivity.this, "User successful created", Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(getApplicationContext(), MenuActivity.class));
                            //Intent intent = new Intent(getApplicationContext(), MenuActivity.class);
                            //intent.putExtra("fullName", fullName);
                            //startActivity(intent);

                        }
                        else {
                            Toast.makeText(RegisterActivity.this, "Error! " +
                                    task.getException().getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });

This is the message error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.xxxxxxx, PID: 5790
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xxxxxxx/com.example.xxxxxxx.activities.MenuActivity}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
     Caused by: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
        at androidx.appcompat.app.AppCompatDelegateImpl.setSupportActionBar(AppCompatDelegateImpl.java:572)
        at androidx.appcompat.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:159)
        at com.example.inbioaiqua.activities.MenuActivity.onCreate(MenuActivity.java:30)
        at android.app.Activity.performCreate(Activity.java:6662)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
        at android.app.ActivityThread.-wrap12(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6077) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 
2 Answers

Welcome to Stackoverflow. I'll be glad to help you but can you please provide us your crash error and your whole RegisterActivity.class, just like you did with MenuActivity.class. There could be many errors and solutions to this but it's hard to answer at first sight.

Also, I would suggest two things before even seeing the rest of the code.

1. Delay startActivity() with timelength of toast message

This will show a toast message to your user that "User is created" and then proceed to MenuActivity.class. This is good practice because your Toast won't cause any problems or won't be shown once you are already on MenuActivity.

To do this just use this:

Handler mHandler = new Handler();
    mHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            Intent intent = new Intent(RegisterActivity.this, MenuActivity.class);
            startActivity(intent);
            finish();
        }

    }, 2000);
//Toast.LENGTH_SHORT = 2000 milisec = 2 seconds
//Toast.LENGHT_LONG = 3500 milisec = 3.5 seconds

2. Show your message in MenuAcitivty.class

If you don't want to delay your startAcitivty() you can simply show your message once a user is on MenuActivity after the registration process is over. To do this you can use intent.putExtra to provide info that the user is coming from RegisterActivity.class.

Intent intent = new Intent(RegisterActivity.this, MenuActivity.class);
intent.putExtra("NEW_USER", true);
startActivity(intent);
finish();

Then in MenuActivity.class in OnCreate just write this.

if (getIntent().hasExtra("NEW_USER") && getIntent().getBooleanExtra("NEW_USER", false)) {
        Toast.makeText(getBaseContext(), "User created succesfully", Toast.LENGTH_SHORT).show();
    }

3. Use theme.xml or styles.xml to remove ActionBar

What is your parent Theme? If you don't want ActionBar then in your base theme in styles.xml write next two lines:

<item name="windowActionBar">false</item> 
<item name="windowNoTitle">true</item>

So your base theme style should look like this:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Or you can simply extend your base theme as NoActionBar Theme and probably solve this issue.

<style name="NoActionBarTheme" parent="Theme.AppCompat.Light.NoActionBar">
 ...
</style>

4. Check your application and activity theme inside AndroidManifest.xml

Check which theme you are using inside AndroidManifest.xml. It could be that your theme is not pointing to the right theme from styles.xml or theme.xml. This can also be changed for each activity so check if you are overriding your theme somewhere.

Try following source code

startActivity(new Intent(getActivity(), MenuActivity.class));

getApplicationContext() doesn't work when you are on fragment. So, you have to try getActivity

Related