Getting error while getting view of RecyclerView in onActivityCreated() - java

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);
}

Related

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

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;

.getView.findViewById in fragment returning NullPointerException [duplicate]

I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = (ImageView)findViewById(R.id.my_image);
return inflater.inflate(R.layout.testclassfragment, container, false);
}
}
The findViewById method has an error on it which states that the method is undefined.
Use getView() or the View parameter from implementing the onViewCreated method. It returns the root view for the fragment (the one returned by onCreateView() method). With this you can call findViewById().
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
// or (ImageView) view.findViewById(R.id.foo);
As getView() works only after onCreateView(), you can't use it inside onCreate() or onCreateView() methods of the fragment .
You need to inflate the Fragment's view and call findViewById() on the View it returns.
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
Inside Fragment class you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
Always remember in case of Fragment that onViewCreated() method will not called automatically if you are returning null or super.onCreateView() from onCreateView() method.
It will be called by default in case of ListFragment as ListFragment return FrameLayout by default.
Note: you can get the fragment view anywhere in the class by using getView() once onCreateView() has been executed successfully.
i.e.
getView().findViewById("your view id");
I realise this is an old question, but the prevailing answer leaves something to be desired.
The question is not clear what is required of imageView - are we passing it back as the view, or merely saving a reference for later?
Either way, if the ImageView is coming from the inflated layout, the correct way to do this would be:
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v;
}
}
Get first the fragment view and then get from this view your ImageView.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
}
Inside Fragment class we get onViewCreated() override method where we should always initialize our views because in this method we get view object. Using this object we can find our views like below:
class MyFragment extends Fragment {
private ImageView imageView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//initialize your view here for use view.findViewById("your view id")
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
You could also do it in the onActivityCreated Method.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
Like they do here: http://developer.android.com/reference/android/app/Fragment.html (deprecated in API level 28)
getView().findViewById(R.id.foo);
and
getActivity().findViewById(R.id.foo);
are possible.
getView() will give the root view
View v = getView().findViewByID(R.id.x);
You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View variables. Here's an example:
class GalleryFragment extends Fragment {
private Gallery gallery;
(...)
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
}
}
The method getView() wont work on fragments outside OnCreate and similar methods.
You have two ways, pass the view to the function on the oncreate (what means you can only run your functions when the view is being created) or set the view as a variable:
private View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}
public void doSomething () {
ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}
1) first inflate layout of Fragment then you can use findviewbyId .
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
return view;
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);
agreed with calling findViewById() on the View.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) V.findViewById(R.id.my_image);
return V;
}
Note :
From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.
So now you can simply do,
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
Use
imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);
imageview = (ImageView) getActivity().findViewById(R.id.imageview1);
it will work
According to the documentation on API level 11
Reference, in Back Stack
http://developer.android.com/reference/android/app/Fragment.html
short code
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
return v;
}
Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.
Try this it works for me
public class TestClass extends Fragment {
private ImageView imageView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
findViews(view);
return view;
}
private void findViews(View view) {
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
1) Declare your layout file.
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
return inflate(R.layout.myfragment, container, false);
}
2)Then, get the id of your view
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView nameView = (TextView) view.findViewById(R.id.textview1);
}
The best way to implement this is as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) rootView.findViewById(R.id.my_image);
return rootView
}
In this way, the rootView can be used for each control defined in the xml layout and the code is much cleaner in this way.
Hope this helps :)
Try This:
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);
return v;
try
private View myFragmentView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentView;
}
Use gradle skeleton plugin, it will automatically generate the view holder classes with the reference to your layout.
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyLayout myLayout = new MyLayout(inflater, container, false);
myLayout.myImage.setImageResource(R.drawable.myImage);
return myLayout.view;
}
}
Now assuming you had an ImageView declared in your my_layout.xml file, it will automatically generate myLayout class for you.
I like everything to be structured. You can do in this way.
First initialize view
private ImageView imageView;
Then override OnViewCreated
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
findViews(view);
}
Then add a void method to find views
private void findViews(View v) {
imageView = v.findViewById(R.id.img);
}
//here you can do it by
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_apple, container,
false);
ist = view.findViewById(R.id.linearLink);
second = view.findViewById(R.id.linearPhone);
return view;
ImageView imageView;
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
imageView = view.findViewById(R.id.my_image);
return view;
}
You can call findViewById() with the Activity Object you get inside your public void onAttach(Activity activity) method inside your Fragment.
Save the Activity into a variable for example:
In the Fragment class:
private Activity mainActivity;
In the onAttach() method:
this.mainActivity=activity;
Finally execute every findViewById through the vairable:
mainActivity.findViewById(R.id.TextView);
Inside onCreateView method
1) first you have to inflate the layout/view you want to add
eg. LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2) Then you can find your imageView id from layout
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)return the inflated layout
return ll;
You have to inflate the view
public class TestClass extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView)v.findViewById(R.id.my_image);
return v
}}
There is one more method called onViewCreated.
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}

I want to use same xml file with two different fragments

I'm new to android programming. I want to write an android program which contains two fragments. Designs' will be same but I can't write layout file twice as it has a lot of widgets so is there a way to handle this?
If I copy xml file widget ids' stay same and I can't reach them in my java class...
Lets assume you have fragment_container.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fraContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
What you need to do is to replace this container with one of the fragments in your program like this for example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_container);
if (findViewById(R.id.fraContainer) != null)
{
MyFragmentA myFragment = new MyFragmentA();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fraContainer, myFragment)
.commit();
}
}
This will replace the fragment layout (container) with the fragment you want.
Now lets examine MyFragmentA, and MyFragmentB
public class MyFragmentA extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_both, container, false);
TextView x = (TextView)view.findViewById(R.id.textView);
x.setText("I am fragment A");
return view;
}
...
And the second fragment
public class MyFragmentB extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_both, container, false);
TextView x = (TextView)view.findViewById(R.id.textView);
x.setText("I am fragment B");
return view;
}
...
Both inflate the same fragment_both.xml, and both use the same TextView with the same ID, by referring to the view object!
I hope that helps you understand it.
You can simply use the same xml file in more fragments, like this:
Fragment A
public class FragmentA extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.your_layout, container, false);
...
return v;
}
}
Fragment B
public class FragmentB extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.your_layout, container, false);
...
return v;
}
}

Android ListView App crash error

I tries to set up a listView in a fragment but my app crashes,tried to search on the internet but couldn't find an answer.
Java Source code:
public static class FragmentFind extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String [] cinemas={
"Cinema 1","Cinema 2","Cinema 3"
};
ArrayAdapter<String> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,cinemas);
ListView list=(ListView) getActivity().findViewById(R.id.cinema_list);
list.setAdapter(adapter);
return inflater.inflate(R.layout.fragment_find,container,false);
}
}
Android XML layout for the fragment
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cinema_list"
android:layout_alignParentTop="true"/>
</RelativeLayout>
Thanks.
Because your ListView is Null. As your Listview is part of Fragment layout you have to call findViewById() on view inflated by that fragment layout file.
So try like,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_find,container,false);
String [] cinemas={"Cinema 1","Cinema 2","Cinema 3"};
ArrayAdapter<String> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,cinemas);
ListView list=(ListView) view.findViewById(R.id.cinema_list);
list.setAdapter(adapter);
return view;
}
I believe the error is probably a null exception. The main differences that I saw from my fragment from yours.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.whatever, container, false);
View testview= (View) v.findViewById(R.id.id);
return v;
}
I suggest you to look at the Difference between onCreateView() and onViewCreated() in Fragment.Even tough you can do do the same thing in onCreateView() method, it is best to do the setting of the Adapter in the onViewCreated() method
This is where the issue is,
ListView list=(ListView) getActivity().findViewById(R.id.cinema_list);
Here is how I would do it.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_find,container,false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState){
String [] cinemas={
"Cinema 1","Cinema 2","Cinema 3"
};
ArrayAdapter<String> adapter=new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,cinemas);
ListView list=(ListView) view.findViewById(R.id.cinema_list);
list.setAdapter(adapter);
}
Your activity does not have the ListView R.id.cinema_list when the app tries to search for it by: getActivity().findViewById(R.id.cinema_list);
So you should better search the ListView within inflated view by:
View view = inflater.inflate(R.layout.fragment_find,container,false);
ListView myList = (ListView)view.findViewById(R.id.cinema_list);
And then set the adapter and return the view .
You are lucky that your app crashed. It is also possible that getActivity().findViewById(R.id.cinema_list) could find a ListView if your activity layout has a ListView with R.id.cinema_list. I am telling this because it is obvious that you will have only one ListView with such specific id, but sometimes people use common ids such as listView1. So you better be careful.
Replace this:
ListView list=(ListView) getActivity().findViewById(R.id.cinema_list);
with this:
ListView list = (ListView) view.findViewById(R.id.cinema_list);

Fragment content does not show up until I switch it and select it again

I've got a problem with my Android app: my fragment content doesn't show up until I switch it and I select it again. What should load just at the fragment start is a list of Cards.
Here you got the onCreate method of the Fragment that loads everything:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
debts = bundle.getParcelableArrayList("list");
adapter = new CardAdapter(getActivity(), android.R.color.holo_blue_dark);
for (int i=0; i<debts.size();++i) {
Debt d = debts.get(i);
Card card = new Card(d.getSecondUser(),d.getSubject());
adapter.add(card);
}
}
And here the onActivityCreated method where i set the adapter for the list:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
CardListView list = (CardListView) getView().findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
}
It works if I use an ArrayList of Cards already loaded, but not this way.
I tried nearly everything... thank you very much.
UPDATE: Even I tried with the solutions you gave me, it keeps happening, my code now:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = this.getArguments();
debts = bundle.getParcelableArrayList("list");
adapter = new CardAdapter(getActivity(), android.R.color.holo_blue_dark);
for (int i=0; i<debts.size();++i) {
Debt d = debts.get(i);
Card card = new Card(d.getSecondUser(),d.getSubject());
adapter.add(card);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_debts, container,
false);
CardListView list = (CardListView) rootView.findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
return rootView;
}
You should initialize your cardListView inside the onCreateView() method. onCreateView() gets called before the onActivityCreated() method. onCreateView() should be the point when the view of your fragment is initialized.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//use your layout file instead of R.layout.fragment_main
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
CardListView list = rootView.findViewById(R.id.newCard);
list.setCardTheme(CardTheme.Light);
list.setAdapter(adapter);
}
Please take a look at the lifecycle of Fragments.

Categories