Search code examples
androidandroid-fragmentsnullpointerexceptionsqliteopenhelper

Getting Context from a fragment - NullPointerException?


I tried to get activity's context from Fragment's onAttach() method.

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

    context = activity.getApplicationContext();

     obj = new MySQLiteHelper(context);
   ...

}

But, I'm still getting NullPointerException. How should I structure my code to avoid this?

Here is my Fragment code :

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             
}

What is the cause of the problem? Can anyone explain me please?


Solution

  • Android provides you a getActivity() in a fragment for the same scenario.

    This is from the documentation for onAttach().The onCreate is called immedaitely after onAttach().

    I think if you check the onCreate(),you could use that instead for your purpose.

    If you carefully read the fragment lifecycle,the activity's onActivityCreated onccurs after onAttach().You need the activity created to get context.So if possible you could shift your code to the onCreate of the fragment.