gregor
gregor

Reputation: 199

Android - Accessing Context with getActivity in ListFragment returns null

I'm trying to write to a sqlite db in a ListFragment, the issue is with getting the Context from within this Fragment.

The strange thing is that calling getActivity() returns the context in the onActivityCreated method but not elsewhere (even after that call). I've even tried storing the context in a class variable mContext from there but the next time I access that variable it's back to null!

Any ideas on what's happening here? Something strange going on in the Fragment lifecycle?

public class DayFragment extends ListFragment {

private String day;
private Context mContext;

public DayFragment() {
}


public String getDay() {
    return day;
}

public void setDay(String day) {
    this.day = day;
}

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

    String[] values = new String[] { day, "Android", "iPhone", "WindowsMobile" };
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, values);

    setListAdapter(adapter);

}

@Override
public void onActivityCreated(Bundle savedInstanceState)
{
    super.onActivityCreated(savedInstanceState);
    mContext = this.getActivity();
}


public void createEntry() {
    EntriesDataSource datasource = new EntriesDataSource(mContext);
    datasource.open();
    Entry entry = new Entry();
    entry.setDay(day);
    entry.setTitle("ok");
    entry.setTime("09:00");
}
}

Upvotes: 1

Views: 3034

Answers (1)

Prmths
Prmths

Reputation: 2032

As per a response in this question and this question, if you haven't attached your fragment yet, it will not return a context.

From the second question:

I'd suggest adding an

onAttach(Activity activity) method to your fragment and putting a break point on it and seeing when it is called relative to your call to 'asd()'. You'll see that it is called after the method where you make the call to 'asd()' exits. The 'onAttach' call is where the fragment is attached to its activity and from this point getActivity() will return non-null (nb there is also an onDetach() call).

Hope this helps.

Upvotes: 1

Related Questions