[duplicate of a similar question]
Asked
Active
Viewed 689 times
2 Answers
0
Fragment's aren't exactly like activities.
You've referenced a View (movieGridView) before onViewCreated has happened, and thus it must be `null.
See here
@Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState != null) { int pos = (Integer) savedInstanceState.getSerializable("POS"); if (!movieDataList.isEmpty()) { movieDataList = Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA")); } // movieGridView.setSelection(pos); // You can't do this here! } }
Besides that, you do not need onCreate at all. savedInstanceState is available within onCreateView.
So, remove that method, and move the code around.
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Added this section
if (movieDataList == null) {
movieDataList = new ArrayList<movieData>();
}
if (savedInstanceState != null) {
index = (Integer) savedInstanceState.getSerializable("POS");
// Not sure why you had 'not empty'
if (movieDataList.isEmpty()) {
movieDataList.addAll(Arrays.asList((movieData[]) savedInstanceState.getSerializable("OLDMOVIEDATA"));
}
} // End restore instance state
View rootView = inflater.inflate(R.layout.movie_display_fragment, container, false);
movieGridView = (GridView) rootView.findViewById(R.id.gv_movie_display);
movieAdapter adapter = new movieAdapter(getActivity(),movieDataList);
movieGridView.setAdapter(adapter);
movieGridView.setSelection(index);
return rootView;
}
You probably want to Bundle.putIntExtra for the "POS", but that is personal preference.
And you should also make MovieData be a Parcelable when you get a chance.
OneCricketeer
- 151,199
- 17
- 111
- 216
-
thank you very much, this fixed the NullPointerException! Great explanation. The setSelection method doesn't set the position right now though, got to fix that now! – Torben Mar 09 '17 at 19:17
-
You had `pos` and `index`. Wasn't sure how to handle that – OneCricketeer Mar 09 '17 at 19:29
-
i save index in the savebundle now with putint and get it in oncreateview with getInt and then use smoothscrolltoposition but it doesn't scroll – Torben Mar 09 '17 at 21:08
-
Not sure what to tell you, but that is a different issue. If you have a new question, please ask it by clicking the [Ask Question](//stackoverflow.com/questions/ask) button. – OneCricketeer Mar 09 '17 at 21:44
-2
initialise
private int index=0;
Since index is not initialised it will be a null value and cause the crash
g7pro
- 807
- 6
- 11