Reputation: 677
I made three Java files in my program. They are MainActivity.java, TrackerDBAdaptor.java, and MyListFragment.java. To access the database I have
private TrackerDBAdapter dbHelper;
dbHelper = new TrackerDBAdapter(this);
When I put the above lines in the MainActivity.java, no problem. But my intention is I'd like to access the database from my MyListFragment.java class. So I put these two lines inside the onCreateView() of the MyListFragment.java. Then "this" inside the
dbHelper = new TrackerDBAdapter(this);
has problem. What I understood is this means the instance of the class calling, why there is difference between MainActivity.java and MyListFragment.java. Thanks.
Upvotes: 0
Views: 656
Reputation: 46
Your class MainActivity.java likely extends the class Activity, which in turn is a descendant of Context. The TrackerDBAdapter.java probably takes a Context in the constructor, which is why passing "this" in MainActivity works. MyListFragment probably extends Fragment, which is not a descendant of Context and therefore passing "this" will not work. One way of obtaining a Context object in a fragment is by calling getActivity(), which returns the Activity object that the fragment is attached to. In other words, doing the following in MyListFragment will probably work.
dbHelper = new TrackerDBAdapter(getActivity())
Beware, though. getActivity() may return null if the fragment is not attached to an activity.
Upvotes: 3
Reputation: 4250
Inside the onCreateView()
of Fragment you need to call like following:
private TrackerDBAdapter dbHelper;
dbHelper = new TrackerDBAdapter(getActivity().getApplicationContext());
Cheers, Happy coding.
Upvotes: 0