Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am getting Null Pointer Exception in GridView Android

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.

like image 702
Intsab Haider Avatar asked Sep 29 '22 19:09

Intsab Haider


1 Answers

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);
like image 116
Giru Bhai Avatar answered Oct 03 '22 01:10

Giru Bhai