Reputation: 203
I am working for the first time with ListFragments. I want to display data from a sqlite database.
My problem: I can't retrieve the context.
I have tried this.getActivity() in my class which extends ListFragment- but the context is null.
Then I have tried to save the context of my first activity(the ui which is displayed after starting the app) of my application as a static variable. But is this the right context?
static Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Setting the context
context = this;
setContentView(R.layout.main);
}
public static Context getContext() {
return context;
}
When I query the database I don't get any exceptions but the cursor is always empty. I have looked into my sqlite database - I have three rows of data (so the cursor should not be empty).
My code for querying the data from the database:
Cursor cursor = null;
try{
open();
cursor = database.rawQuery("select _id, surname, prename, street, zipcode, telephone, email from "+Database.getMyDbTable()+";", null);
}catch(Exception ex){
Log.e(TAG, "Could not get list");
CharSequence text = "Die Liste kann nicht erstellt werden!";
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
Log.d(TAG, "Cursor "+cursor);
close();
How do I get the right context?
Upvotes: 1
Views: 3684
Reputation: 523
Thanks for your answer! I confirmed that I can also solve the same issue by using...
Context myContext = getActivity();
Apparently ListPreference(this) will not work from inside of a PreferenceFragment.
Upvotes: 0
Reputation: 203
I found this tutorial, which was quite helpful (as I wanted to have a Tab Layout combined with a list):
https://github.com/artem-zinnatullin/Android-List-Fragment-Tutorial
I have modified the onCreate method:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Getting the data from the Database
Context myContext = getActivity();
Log.d(TAG, "Context "+myContext);
contactListManager = new ContactList(myContext);
Log.d(TAG, "ContactListManager "+contactListManager);
Cursor cursor = contactListManager.fetchAllItems();
Log.d(TAG, "Cursor "+cursor);
with this code I can access my database.
Upvotes: 2