java.lang.NullPointerException: Error while using RecyclerView.Widget - java

I am trying to add a list of audio files to my fragment. I have also set the layout manager to recycler view. I have also added dependencies to gradle build
Here is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View androidx.recyclerview.widget.RecyclerView.findViewById(int)' on a null object reference
at com.example.musicplayer.AllSongs.onCreateView(AllSongs.java:35)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
I am trying to get all songs in my all songs fragment.
Here is my code which shows error:
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
recyclerView = recyclerView.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
if (!(musicFiles.size() < 1))
{
musicAdapter = new MusicAdapter(getContext(),musicFiles);
recyclerView.setAdapter(musicAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
return inflater.inflate(R.layout.fragment_all_songs_tab, container, false);
}

Your app is crash at below line
recyclerView.findViewById(R.id.recyclerView);
Do as per below
onCreateView(.....){
View v = inflater.inflate(R.layout.fragment_all_songs_tab, container, false);
recyclerView = v.findViewById(R.id.recyclerView);
....
....
return v ;
}

Try with
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_all_songs_tab, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
musicFiles = new ArrayList();
if (!(musicFiles.size() < 1))
{
musicAdapter = new MusicAdapter(getContext(),musicFiles);
recyclerView.setAdapter(musicAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
}
return view;
}

the error is fixed here is the solution
What I have done:
earlier I was returning onCreateView function but after returning inflater in View my code was fixed and list of audio files was shown
View view = inflater.inflate(R.layout.fragment_all_songs_tab, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
musicAdapter = new MusicAdapter(getContext(), musicFiles);
recyclerView.setAdapter(musicAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
musicAdapter.notifyDataSetChanged();
return view;

Related

Getting error while getting view of RecyclerView in onActivityCreated()

I am following a tutorial on Udemy using RecyclerView using Fragments. Everything works fine until this line 44 recyclerView = view.findViewById(R.id.rcl)
I searched a lot on internet but did not get any solution related to this. I debugged the code and view was null. Either there was a problem in that tutorial or only i am having the problem.
1- Fragment_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".ListFrag">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rcl"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
2- ListFrag.jave
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Inflate the layout for this fragment
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = view.findViewById(R.id.rcl);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
recyclerView.setAdapter(adapter);
}
3- This is the Error :
Error :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.example.recyclerfragments.ListFrag.onActivityCreated(ListFrag.java:44)
at androidx.fragment.app.Fragment.performActivityCreated(Fragment.java:2619)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:904)
at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2659)
at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:201)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
at android.app.Activity.performStart(Activity.java:7214)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3189)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:185)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:170)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:147)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:73)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2031)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7083)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:536)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
Error is here:
recyclerView = view.findViewById(R.id.rcl);
view is null.
Try to replace by:
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
// Add this.. Here, view won't be null
recyclerView = view.findViewById(R.id.rcl);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// recyclerView = view.findViewById(R.id.rcl); --> Remove this from here.
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
recyclerView.setAdapter(adapter);
}
Another options is replacing view by getActivity():
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView = getActivity().findViewById(R.id.rcl);
....
}
put your code in onViewCreated() this is for kotlin, for java just override the method and put your code in it
make sure your view object is globally declared so it will not be null after view created
like this:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerView = view.findViewById(R.id.rcl)
recyclerView.setHasFixedSize(true)
layoutManager = LinearLayoutManager(this.activity)
recyclerView.setLayoutManager(layoutManager)
adapter = PersonAdapter(this.activity, ApplicationClass.people)
recyclerView.setAdapter(adapter)
}
You are initializing view in onCreateView but using view recyclerView = view.findViewById(R.id.rcl); in onActivityCreated, thats why you are getting error.
There are multiple ways to resolve this error:
First One:
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
recyclerView = view.findViewById(R.id.rcl);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
recyclerView.setAdapter(adapter);
return view;
}
2nd :
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
recyclerView = view.findViewById(R.id.rcl);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this.getActivity());
recyclerView.setLayoutManager(layoutManager);
adapter = new PersonAdapter(this.getActivity(), ApplicationClass.people);
recyclerView.setAdapter(adapter);
}

why setVisibility in fragment doesn't work?

the ProgressBar doesn't disappear in the fragment also items aren't loaded in the RecyclerView, When the code was in the body of onCreate of the main activity ,it was working
I am making fragment that contains ProgressBar and RecyclerView with retrieving data from firebase database , I added setVisibility at the end of onDataChange method so that after getting all the data and store it in the array list , the ProgressBar disappear
RecyclerView offersRecycler;
ArrayList<offer> offers;
OffersAdapter offersAdapter;
View fragment_layout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragment_layout = inflater.inflate(R.layout.fragment_offers, container, false);
// Offers RecyclerView
offersRecycler = fragment_layout.findViewById(R.id.offersRecycler);
offers = new ArrayList();
offers_init();
offersAdapter = new OffersAdapter(offers,getContext());
offersRecycler.setAdapter(offersAdapter);
offersRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_offers, container, false);
}
private void offers_init() {
DatabaseReference db_offers = db_ref().child("offers");
db_offers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
ProgressBar loadingOffers = fragment_layout.findViewById(R.id.loadingOffers);
loadingOffers.setProgress(10);
for (DataSnapshot offer_item : dataSnapshot.getChildren()) {
String id = offer_item.getKey();
String title = offer_item.child("title").getValue().toString();
String rating = offer_item.child("rating").getValue().toString();
String orders_number = offer_item.child("orders_number").getValue().toString();
offer offer_object = new offer(id,title, rating, orders_number);
offers.add(offer_object);
offersAdapter.notifyDataSetChanged();
}
Toast.makeText(getContext(),"title",Toast.LENGTH_LONG).show();
loadingOffers.setVisibility(View.GONE);
}catch (Exception ex){
Toast.makeText(getContext(),ex.getMessage(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
}
I expect the ProgressBar to hide and the array loaded into the RecyclerView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragment_layout = inflater.inflate(R.layout.fragment_offers, container, false);
// Offers RecyclerView
offersRecycler = fragment_layout.findViewById(R.id.offersRecycler);
offers = new ArrayList();
offers_init();
offersAdapter = new OffersAdapter(offers,getContext());
offersRecycler.setAdapter(offersAdapter);
offersRecycler.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_offers, container, false);
}
^ This is your code snippet. What you are doing is - inflating a layout fragment_layout = inflater.inflate(R.layout.fragment_offers, container, false) and using fragment_layout to get the instance of RecyclerView. This is fine.
But at the end of the method, you are inflating a new layout and returning that. So the Android framework uses that View instead of fragment_layout to set the Fragment view. All the views in fragment_layout won't be shown since it's never added to the fragment and hence you don't see any changes in the RecyclerView.
At the end of the onCreateView method, you should just return fragment_layout.
in your CreateView, change
return inflater.inflate(R.layout.fragment_offers, container, false);
by
return fragment_layout;
You call the layout, init recyclerview, but recall the "blank" layout
Also, avoid underscore for method or variable name, it's not the java convention

RecyclerView displaying no items and calling none of the custom Adapter's functions [duplicate]

I want to display recycler view inside fragment but i am getting java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v7.widget.RecyclerView$LayoutManager.canScrollVertically()' on a null object reference. . Code is given below .
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
final LinearLayoutManager layoutManager = new LinearLayoutManager(this.getContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
ArrayList<String> values = getArguments().getStringArrayList("arrayList");
RecyclerViewAdapter cl = new RecyclerViewAdapter(ctx, values);
recyclerView.setAdapter(cl);
return inflater.inflate(R.layout.fragment_blank, container, false);
}
Try using:
final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
I think your context is not passed in constructing linearlayoutmanager
You are creating a view (in the first line) and you are ignoring it and returning something else.
You should do this :
return(rootview)

How to call a tabbed activity fragment from main activity?

I have selected a tabbed activity template with "Action bar tabs" in android studio.
Then i had created three fragments (One.java, Two.java, Three.java) one for each of the tabs.
I have the code related to the cursors in the second fragment.The thing is when i run the application the code in the second fragment is not being executed.
My question is will the fragment (Two.java) will be called implicitly or it is needed to call by creating an instance (if yes, how?).
code snippet for MainActivity.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1){
View rootView = inflater.inflate(R.layout.fragment_one, container, false);
return rootView;
}
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
View rootView = inflater.inflate(R.layout.fragment_two, container, false);
return rootView;
} else {
View rootView = inflater.inflate(R.layout.fragment_three, container, false);
return rootView;
}
}
code snippet for Two.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
logReader1 = new LogReader(getContext());
db = logReader1.getReadableDatabase();
Cursor logCursor = db.rawQuery("SELECT rowid _id,name,Time_Used,app_Image FROM logs ORDER BY Time_Used DESC", null);
LogCursorAdapter logAdapter = new LogCursorAdapter((MainActivity) getContext(), logCursor);
ListView log_Items = (ListView) container.findViewById(R.id.list_item);
log_Items.setAdapter((logAdapter));
return log_Items;
}
From what I can tell you aren't actually creating a new fragment. You're inflating the layout that you're intending to use as the layout for the fragment two.
Something like https://developer.android.com/training/implementing-navigation/lateral.html should get you pointed in the right direction. Notice how they create and return a fragment in the DemoCollectionPagerAdapter.

FlipView Adapter not Updating

The adapter of a flipview is set onCreate. Everything works fine. The user is meant to select some items on another activity which would update the items on the flipview. I implemented this by changing the adapter of the flipView when onResume is called and the dismiss activity is the selectionActivity. The code is executed but it does not reflect on the flipView items.
What i do on onCreate
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.flip_main, container, false);
mFlipView = (FlipView) rootView.findViewById(R.id.flip_view);
mAdapter = new FlipAdapter(getActivity(),getHomeItems(), getFragmentManager());
mAdapter.setCallback(this);
mFlipView.setAdapter(mAdapter);
mFlipView.setOnFlipListener(this);
if (isFirstShown) {
mFlipView.peakNext(false);
isFirstShown = false;
}
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(getActivity().findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
return rootView;
}
what is called after the user makes selection
FlipAdapterTest mAdapter = new FlipAdapterTest(getActivity(), getHomeItems(), getFragmentManager());
mFlipView.removeAllViews();
mFlipView.setAdapter(mAdapter);

Categories