jkdobariya
jkdobariya

Reputation: 146

How to resolve error findViewById error in android fragment

I'm trying to add recyclerview in my fragment but I'm getting error when I click on navigation drawer item.

Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference at com.example.myapplication.fragment.Books.onCreate(Books.java:45)

How to resolve error or suggest tutorial to load json data in fragment using recyclerview. with click event on recyclerview. on click item open new fragment with data.

This is my code

public class Books extends Fragment {

    private BooksModel booksViewModel;

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    private List<BooksModel> bookLists;
//    Context context;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        recyclerView = (RecyclerView) getView().findViewById(R.id.recyclerViewBook); //Line 45 Error
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        bookLists = new ArrayList<>();

        for(int i=0; i<=10; i++){
            BooksModel bookList = new BooksModel(
                    "",
                    "Title " + (i + 1),
                    "This is Auther"
            );

            bookLists.add(bookList);

            adapter = new BooksAdapter(bookLists,this);
            recyclerView.setAdapter(adapter);
        }
    }

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        booksViewModel =
                new ViewModelProvider(this).get(BooksModel.class);
        View root = inflater.inflate(R.layout.fragment_books, container, false);
        final TextView textView = root.findViewById(R.id.text_book );
        booksViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

Upvotes: 0

Views: 79

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199825

onCreate() runs before onCreateView(). You should move all of that code to onViewCreated(), which passes you the View directly (meaning you don't have to call getView() at all).

Upvotes: 1

Related Questions