-6

I want to use my database adapter in my list fragment to get all entities from a table to put into the listview, but when I try to construct it during the fragment creation I get the message that context can't be applied to my fragment.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DbAdapter db = new DbAdapter(this); //error message here
    }

However, I don't get an error message when I put the adapter in my activity.

How can I get the activity that my fragment is in so I can use it as the context? Or alternatively, is there a better way to do this?

Friso
  • 2,328
  • 9
  • 36
  • 72
  • 4
    There is a method `getActivity()` on `Fragment`. `DbAdapter db = new DbAdapter(getActivity());` – George Mulligan Jan 31 '16 at 02:58
  • Possible duplicate of [Using context in fragment](http://stackoverflow.com/questions/8215308/using-context-in-fragment) – Deduplicator Jan 31 '16 at 12:00
  • What is the *exact* error message you get? That should be fleshed out; it seems like it might be something to do with context cannot be applied; but the way your question is formatted it's hard to be sure. – George Stocker Jan 31 '16 at 19:36

1 Answers1

4

It's simple. You can get the activity your fragment is in by using:

getActivity();

Your code should be:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    DbAdapter db = new DbAdapter(getActivity()); // Replace this with getActivity()
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arnab Jain
  • 247
  • 1
  • 5
  • 3
    Try not to store your Activity instance/reference for memory leak purposes. – TheSunny Jan 31 '16 at 03:46
  • 1
    That's just for example for his understanding. I have added what his actual code should have been. I personally never store the acticity instance. – Arnab Jain Jan 31 '16 at 03:48