从片段获取上下文 - NullPointerException?

Getting Context from a fragment - NullPointerException?

我试图从 FragmentonAttach() 方法中获取 activity 的 context

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    context = activity.getApplicationContext();

     obj = new MySQLiteHelper(context);
   ...

}

但是,我仍然得到 NullPointerException我应该如何构建我的代码以避免这种情况?

这是我的片段代码:

public class ListTab extends Fragment {

    View view;

    Context context ;       // I just created reference here
    MySQLiteHelper obj;    // and initialised in onAttach()

    String[][] table;
    byte[][] images;
    Bitmap[] bitmap;

    String[] title = new String[10];
    String[] init_price = new String[10];
    String[] cur_price = new String[10];    

    int len,i;

    private OnFragmentInteractionListener mListener;

    public ListTab() {
        // Required empty public constructor
    }

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

     // not sure when this is called, so left this empty.
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_list_items, container, false);

        obj.open(); //I'm getting an exception here - NullPointerException
        obj.read();

        table = obj.getTable();
        images = obj.getImages();

        len = obj.getLength();

      ...
      //some code to inflate fragment with Listview

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        context = activity.getApplicationContext();

        obj = new MySQLiteHelper(context);
     ...
     //some code
    }

 ... 
// some other methods             
}

问题的原因是什么?谁能给我解释一下?

Android 在同一场景的片段中为您提供 getActivity()

这来自 onAttach() 的文档。onCreate 在 onAttach() 之后立即调用。

我认为如果您检查 onCreate(),您可以将其用于您的目的。

如果您仔细阅读 fragment lifecycle,activity 的 onActivityCreated 在 onAttach() 之后发生。如果可能,您需要创建 activity 以获得 context.So可以将您的代码转移到片段的 onCreate