I am getting null pointer exception in fragment using Gridview
.
My code is
public class HomeFragment extends Fragment {
GridView grid;
String[] web = { "Bata", "Service", "puma", "Hush" };
int[] imageId = { R.drawable.shoesmall, R.drawable.shoe1, R.drawable.shoe3,
R.drawable.shoe4 };
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_home, container);
CustomGrid adapter = new CustomGrid(getActivity().getApplicationContext(), web, imageId);
grid = (GridView) getView().findViewById(R.id.gridview);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity().getApplicationContext(),
"You Clicked at " + web[+position], Toast.LENGTH_SHORT)
.show();
}
});
return rootView;
}
}
Can anyone guide why it is happing? I don't use fragments commonly.
your getView()
is null,because view not yet created,So change
grid = (GridView) getView().findViewById(R.id.gridview);
to
grid = (GridView) rootView.findViewById(R.id.gridview);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With