android intent在gridview setonitemclickListener事件中给出NullPointerException

时间:2016-02-25 04:23:17

标签: android gridview

Android意图在gridview setonitemclickListener事件中提供 NullPointerException

public class GridFragment extends Fragment {

    GridView mGridView;
    private GridAdapter mGridAdapter;
    GridItems[] gridItems = {};
    private Activity activity;

    public GridFragment(GridItems[] gridItems, Activity activity) {
        this.gridItems = gridItems;
        this.activity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View view;
        view = inflater.inflate(R.layout.grid, container, false);
        mGridView = (GridView) view.findViewById(R.id.gridView);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (activity != null) {

            mGridAdapter = new GridAdapter(activity, gridItems);
            if (mGridView != null) {
                mGridView.setAdapter(mGridAdapter);
            }

             mGridView.setOnItemClickListener(new OnItemClickListener() {
                 @Override
                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                     PackageManager pacmanager=getActivity().getPackageManager();

                     Intent i=pacmanager.getLaunchIntentForPackage(gridItems[position].title.toString());
                     getActivity().startActivity(i);

                 }
             });
         }
     }

我的错误就是这个。

  

显示java.lang.NullPointerException

我在网上收到错误,

getActivity().startActivity(i);

怎么了?

3 个答案:

答案 0 :(得分:0)

您需要替换getActivity().startActivity(i); MainActivity.this.startActivity(i);

快速修复

mGridView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {
       PackageManager pacmanager=getActivity().getPackageManager();
       Intent i=pacmanager.getLaunchIntentForPackage(gridItems[position].title.toString());
        MainActivity.this.startActivity(i);

    }
   });

答案 1 :(得分:0)

如果你的意图是正确的,那么你的getActivity()会返回null,

你可以尝试mainactivity.startActivity(i);

YourParentActivity mainactivity;

@Override
public void onAttach(Activity activity) {
    mainActivity = (YourParentActivity ) activity;

    super.onAttach(activity);
}

答案 2 :(得分:0)

如果要在此片段附加到Container Activity时启动Activity,则必须使用onAttach方法。

public void onAttach(Activity activity) {
    super.onAttach(activity);
    // use this activity
}

如果您要开始其他活动,可以使用activity.startActivity()getApplicationContext().startActivity(intent);

希望这有帮助。