Dhruv Modi
Dhruv Modi

Reputation: 1

How do I fix this error in navController MainActivity?

Illegal State Exception error... I can't understand...How do I fix MainActivity does not have a navcontroller?

I just got my code to compile and when I try to start the app I receive the error. I'm currently trying to setup Fragments for my class project. Not sure why I'm getting this output...

Error:-

 Caused by: java.lang.IllegalStateException: Activity com.example.instagramclone.MainActivity@6a5f3da does not have a NavController set on 2131362023

My MainAcivity.java:-

package com.example.instagramclone;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.example.instagramclone.ui.home.HomeFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class MainActivity extends AppCompatActivity {

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

        BottomNavigationView navView = findViewById(R.id.nav_view);
        NavController navController = Navigation.findNavController(this,R.id.nav_host_fragment);

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

        ImageView cameraToolbar = toolbar.findViewById(R.id.camera);

        cameraToolbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(MainActivity.this, "CAMERA", Toast.LENGTH_SHORT).show();

            }
        });

        navView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                if(menuItem.getItemId() == R.id.navigation_home)
                {

                    HomeFragment homeFragment = new HomeFragment();
                    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                    transaction.replace(R.id.nav_host_fragment , homeFragment);
                    transaction.commit();
                }

                else if (menuItem.getItemId() == R.id.search) {
                    Toast.makeText(MainActivity.this, "SEARCH", Toast.LENGTH_SHORT).show();
                }



                return true;
            }
        });
    }
}                

My activity_main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@color/white2"
        android:elevation="10dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal">

            <ImageView
                android:id="@+id/camera"
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="10dp"
                android:padding="5dp"
                app:srcCompat="@drawable/camera"
                android:contentDescription="TODO" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_weight="1"
                android:fontFamily="@font/bilbo_swash_caps"
                android:gravity="center|center_vertical"
                android:padding="5dp"
                android:text="Instagram"
                android:textColor="#000000"
                android:textSize="25sp"
                android:textStyle="bold" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="10dp"
                android:contentDescription="TODO"
                android:padding="5dp"
                app:srcCompat="@drawable/igtv"
                app:tint="@color/textcolor" />

            <ImageView
                android:layout_width="40dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="5dp"
                android:layout_marginEnd="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="10dp"
                android:padding="5dp"
                app:srcCompat="@drawable/send" />

        </LinearLayout>


    </androidx.appcompat.widget.Toolbar>


    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:labelVisibilityMode="selected"
        app:menu="@menu/bottom_nav_menu" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/nav_view"
        android:layout_below="@+id/toolbar"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/nav_view"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/mobile_navigation">

    </androidx.fragment.app.FragmentContainerView>

</RelativeLayout>

Error:-

Caused by: java.lang.IllegalStateException: Activity com.example.instagramclone.MainActivity@6a5f3da does not have a NavController set on 2131362023

at com.example.instagramclone.MainActivity.onCreate(MainActivity.java:29)

Upvotes: 0

Views: 1195

Answers (2)

ianhanniballake
ianhanniballake

Reputation: 199805

As per this issue, this is expected when you're using Navigation.findNavController() and FragmentContainerView together and trying to access the NavController in the onCreate() method of your activity.

Navigation.findNavController() relies on the fragment's view to already exist by the time it is called (that's why it takes the ID of a view where your fragment is located). However, when using a FragmentTransaction or FragmentContainerView (which uses a FragmentTransaction to add the NavHostFragment to your layout), the Fragment's view isn't created yet in the onCreate() of the activity. Therefore, findNavController() has no View to find and, hence, your error.

As per the 4th comment on that issue, you can retrieve the NavController directly from the NavHostFragment (as while the Fragment's view hasn't be created yet, the Fragment itself has been):

BottomNavigationView navView = findViewById(R.id.nav_view);

NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager()
    .findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();

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

Upvotes: 1

YZN
YZN

Reputation: 133

You don't need to use this in your code if you are using the navigation controller

            HomeFragment homeFragment = new HomeFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.nav_host_fragment , homeFragment);
            transaction.commit();

instead, consider using this

Navigation.findNavController(it).navigate(YOUR ACTION)

and consider checking this link docutmentation and for a tutorial for using navHost correctly consider watching this nav host documentation

Upvotes: 0

Related Questions