I have followed a tutorial to populate data from an sqlite database in to a spinner (dropdown) in Android. However, I am getting the error:
Cannot make a static reference to the non开发者_运维知识库-static method fetchAllCategories() from the type DatabaseAdapter
My code is as follows:
In EditTask:
private void fillData() {
Cursor categoriesCursor;
Spinner categoriesSpinner = (Spinner) findViewById(R.id.spinDept);
categoriesCursor = DatabaseAdapter.fetchAllCategories();
startManagingCursor(categoriesCursor);
String[] from = new String[] { DatabaseAdapter.CAT_NAME };
int[] to = new int[] { R.id.tvDBViewRow }; //this part hasnt been implemented in to the layout yet
SimpleCursorAdapter categoriesAdapter = new SimpleCursorAdapter(this,
R.layout.db_view_row, categoriesCursor, from, to);
categoriesSpinner.setAdapter(categoriesAdapter);
}
And in my DatabaseAdapter class I have the following:
public Cursor fetchAllCategories() {
if (mDb == null) {
this.open();
}
String tableName = "CAT_TABLE";
return mDb.query(tableName, new String[] { CAT_ID, CAT_NAME }, null,
null, null, null, null);
}
The offending line of code is:
categoriesCursor = DatabaseAdapter.fetchAllCategories();
I'm pretty new to Java/Android so it may be something simple/obvious but any help is much appreciated!
You have to first instantiate a DatabaseAdapter object. eg:
DatabaseAdapter myDbAdapter = new DatabaseAdapter();
categoriesCursor = myDbAdapter.fetchAllCategories();
to be able to make your code work, you need to declare the method fetchAllCategoires() as static as follows:
public static Cursor fetchAllCategories()
Because you have not instantiated a DatabaseAdapter object, you cannot just call one of it's methods by a class name reference unless the keyword static appears in the method declaration.
精彩评论