简体   繁体   中英

Cannot include a RecyclerView inside a Navigation Drawer Fragment

I've been trying to display a CardView list inside the first Fragment of a Navigation Drawer. I'm currently using the Navigation Drawer template from Android Studio.

I have no trouble when defining the fragments, they are shown correctly within the Navigation Drawer, but when it's time to include a RecyclerView, I receive a java.lang.NullPointerException

Here is the MainActivity

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

public DrawerLayout drawer;
public Toolbar toolbar;
public NavigationView navigationView;

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

    //Initialize Fragment
    QuestListFragment fragment = new QuestListFragment();
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();

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

    // DrawerLayout
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

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

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        QuestListFragment fragment = new QuestListFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    } else if (id == R.id.nav_gallery) {
        TestFragment fragment = new TestFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}}

And the QuestListFragment

public class QuestListFragment extends Fragment {

private RecyclerView mQuestRecyclerView;


public QuestListFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_quest, container, false);

    // RecyclerView
    mQuestRecyclerView = (RecyclerView) view.findViewById(R.id.quest_recycler_view);
    mQuestRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return view;
}}

I have tried different ways to implement the RecyclerView but all of them end up in Fatal Exception just by declaring it. An empty Fragment should be seen instead of this error.

Thanks in advance.

EDIT:

Here is the XML where the fragment_container is located, "app_bar_main".

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context="es.smoreno.tfg.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"/>

</android.support.design.widget.AppBarLayout>

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></FrameLayout>

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email"/>

</android.support.design.widget.CoordinatorLayout>

The fragment_quest.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         tools:context=".QuestListFragment">


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="List Quest"
    android:id="@+id/textView2"
    android:layout_gravity="center"/>

And this is the full Logcat

04-11 22:31:13.178 2358-2358/es.smoreno.tfg E/AndroidRuntime: FATAL EXCEPTION: main
                                                      Process: es.smoreno.tfg, PID: 2358
                                                      java.lang.RuntimeException: Unable to start activity ComponentInfo{es.smoreno.tfg/es.smoreno.tfg.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                          at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                          at android.os.Handler.dispatchMessage(Handler.java:102)
                                                          at android.os.Looper.loop(Looper.java:148)
                                                          at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView$LayoutManager)' on a null object reference
                                                          at es.smoreno.tfg.QuestListFragment.onCreateView(QuestListFragment.java:34)
                                                          at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                          at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:742)
                                                          at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                          at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
                                                          at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
                                                          at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1237)
                                                          at android.app.Activity.performStart(Activity.java:6253)
                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                          at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                          at android.os.Looper.loop(Looper.java:148) 
                                                          at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

您的fragment_quest.xml中没有RecyclerView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM