ANDRO ANDRO - 23 days ago 8
Android Question

get NullPointerException in ViewPager

public class News extends Fragment {
private View view;
private ListView listView;
private JSONObject jsonObject;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.news_fragment,container,false);
listView= (ListView) view.findViewById(R.id.listView);
setHasOptionsMenu(true);
return view;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser){
if (isVisibleToUser) getActivity().getActionBar().setTitle(getResources().getStringArray(R.array.homeMenuItems)[4]);
MyCreate();
}
}

public void MyCreate(){
listView.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return 6;
}

@Override
public Object getItem(int position) {
return null;
}

@Override
public long getItemId(int position) {
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView==null){
convertView=getActivity().getLayoutInflater().inflate(R.layout.news_adapter,null);
}
return convertView;
}
});
}
}


When you start it, you get this error:

java.lang.NullPointerException
at com.EraNewGames.Elbase.homeFragments.News.setUserVisibleHint(News.java:38)
at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1103)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:551)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:513)
at android.support.v4.view.ViewPager.setCurrentItem(ViewPager.java:505)
at com.EraNewGames.Elbase.HomeActivity$2.onItemClick(HomeActivity.java:92)


I realized how out of this error, the problem misrepresented that lost link to listView.
But what then ... Not only I have to use Fragments Yes, so not to create fragments of the left and right , as every piece is a method that uses the Internet .
And this is the extra traffic.
To this was not, I decided to check if the window is active then use it .

Why does the
ListView
get
NullPointerException
?

Answer

setUserVisibleHint() is called before onCreateView(), therefore the list view is not initialised.