title: Getting Context from a fragment - NullPointerException?
body: <p>I tried to get activity's <code>context</code> from <code>Fragment</code>'s <code>onAttach()</code> method.</p>
  
  <pre><code>@Override
  public void onAttach(Activity activity) {
      super.onAttach(activity);
  
      context = activity.getApplicationContext();
  
       obj = new MySQLiteHelper(context);
     ...
  
  }
  </code></pre>
  
  <p>But, I'm still getting <code>NullPointerException</code>. <strong>How should I structure my code to avoid this?</strong></p>
  
  <p><strong>Here is my Fragment code :</strong> </p>
  
  <pre><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             
  }
  </code></pre>
  
  <p>What is the cause of the problem? Can anyone explain me please?</p>