Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView : Attempt to invoke virtual method on a null object reference

I have a problem when I try to test my app, I'm a begginer in Android Studio and tried to put a reyclerview in a fragment but when I compile I get this message :

 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

Here is the file that is the cause :

package e.user.popcorn;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toolbar;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
private BottomNavigationView mBottomNavigation;
private FrameLayout mMainFrame;

private HomeFragment homeFragment;
private MoviesFragment moviesFragment;
private UsersFragment usersFragment;
private ChatFragment chatFragment;
private SweetsFragment sweetsFragment;

List<Movie_data> bo_movies;

TextView mTopBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
    BottomNavigationViewHelper.removeShiftMode(bottomNavigationView);

    mMainFrame = (FrameLayout) findViewById(R.id.main_frame);
    mBottomNavigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);


    homeFragment = new HomeFragment();
    moviesFragment = new MoviesFragment();
    usersFragment = new UsersFragment();
    chatFragment = new ChatFragment();
    sweetsFragment = new SweetsFragment();

    bo_movies = new ArrayList<>();
    bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
    bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
    bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
    bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
    bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));

    RecyclerView myRv = (RecyclerView) findViewById(R.id.recyclerView_id);
    RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,bo_movies);
    myRv.setLayoutManager(new GridLayoutManager(this,3));
    myRv.setAdapter(myAdapter);

    setFragment(homeFragment);
    mTopBar = (TextView) findViewById(R.id.top_bar_title);
    mTopBar.setText(R.string.nav_item_home);

    mBottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {

                case R.id.nav_home :
                    setFragment(homeFragment);
                    mTopBar = (TextView) findViewById(R.id.top_bar_title);
                    mTopBar.setText(R.string.nav_item_home);
                    return true;

                case R.id.nav_movies :
                    setFragment(moviesFragment);
                    mTopBar = (TextView) findViewById(R.id.top_bar_title);
                    mTopBar.setText(R.string.nav_item_movies);
                    return true;

                case R.id.nav_users :
                    setFragment(usersFragment);
                    mTopBar = (TextView) findViewById(R.id.top_bar_title);
                    mTopBar.setText(R.string.nav_item_users);
                    return true;

                case R.id.nav_chat :
                    setFragment(chatFragment);
                    mTopBar = (TextView) findViewById(R.id.top_bar_title);
                    mTopBar.setText(R.string.nav_item_chat);
                    return true;

                case R.id.nav_sweets :
                    setFragment(sweetsFragment);
                    mTopBar = (TextView) findViewById(R.id.top_bar_title);
                    mTopBar.setText(R.string.nav_item_sweets);
                    return true;

                default :
                    return false;

            }


        }

    });

}


private void setFragment(Fragment fragment) {

    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.main_frame, fragment);
    fragmentTransaction.commit();

}
}

Here is the fragment_home.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".HomeFragment"
    android:background="@color/colorMainBackgroundDark">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"></LinearLayout>

    <TextView
        android:id="@+id/title_latest_trailers"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_latest_trailers"
        android:textSize="20sp"
        android:textAlignment="center"
        android:layout_margin="16dp"
        android:textColor="@color/colorWhite"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/video_frame"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:background="@color/colorWhite"
        android:contentDescription="TODO"
        android:layout_below="@+id/title_latest_trailers"/>

    <TextView
        android:id="@+id/title_box_office"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title_latest_trailers"
        android:textSize="20sp"
        android:textAlignment="center"
        android:layout_margin="16dp"
        android:textColor="@color/colorWhite"
        android:textStyle="bold"
        android:layout_below="@+id/video_frame"/>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/title_box_office">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

And here is the HomeFragment.java

public class HomeFragment extends Fragment {

    Toolbar mTopBar;

    List<Movie_data> bo_movies;

    public HomeFragment() {


        bo_movies = new ArrayList<>();
        bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
        bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
        bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
        bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));
        bo_movies.add(new Movie_data("Avengers", "Action", "Description de ouf", R.drawable.test));



        // Required empty public constructor

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        RecyclerView myRv = (RecyclerView) findViewById(R.id.recyclerView_id);
        RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,bo_movies);
        myRv.setLayoutManager(new GridLayoutManager(this,3));
        myRv.setAdapter(myAdapter);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

}

I tried changing the layoutmanager but can't find the solution at the moment ...

If you need more informations just ask me and I'll provide all you need.

Thanks for your help !

like image 860
Daniel Morena Avatar asked Apr 18 '18 18:04

Daniel Morena


People also ask

How do I fix null object reference in Android?

So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, the debuggger will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

What is RecyclerView in Android with example?

RecyclerView is the ViewGroup that contains the views corresponding to your data. It's a view itself, so you add RecyclerView into your layout the way you would add any other UI element. Each individual element in the list is defined by a view holder object.


1 Answers

You are getting a NPE because the RecyclerView is in the layout of the Fragment, but the code is looking for it in the layout of the Activity.

This line

RecyclerView myRv = (RecyclerView) findViewById(R.id.recyclerView_id);

Is looking for a View with the id recyclerView_id in the layout activity_main that is set here

setContentView(R.layout.activity_main);

If you want to put the RecyclerView inside a Fragment, you will need to put the RecyclerView code inside the Fragment class. So following lines would go in the Fragment class

RecyclerView myRv = (RecyclerView) findViewById(R.id.recyclerView_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,bo_movies);
myRv.setLayoutManager(new GridLayoutManager(this,3));
myRv.setAdapter(myAdapter);

And in the Fragment you would set fragment_home as your layout

public View onCreateView(...) {
    return inflater.inflate(R.layout.fragment_home, container, false);
}
like image 101
aneurinc Avatar answered Oct 10 '22 14:10

aneurinc