我在这个类中得到db无法被重新发送的错误。在displayListView()函数中。任何人都可以帮我解决它。感谢
从此处获取代码http://kdehairy.com/2012/08/19/using-a-preloaded-sqlite-database-with-sqliteopenhelper/
公共类PrepopSqliteDbActivity扩展了Activity {
// private static final String DB_NAME = "hymnals";
//A good practice is to define database field names as constants
private SimpleCursorAdapter dataAdapter;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Our key helper
ExternalDbOpenHelper repo = ExternalDbOpenHelper.getInstance( context );
SQLiteDatabase db = repo.getWritableDatabase();
displayListView();
}
private void displayListView() {
//all hymns are fetched
*final Cursor cursor = db.fetchAllHymns();*
// The desired columns to be bound
String[] columns = new String[] {
ExternalDbOpenHelper.HYMN_ID,
ExternalDbOpenHelper.HYMN_NAME,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.tVid,
R.id.name,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_main,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.list);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
}
});
}
}
答案 0 :(得分:0)
变量db
是onCreate
方法中的局部变量。请改用实例变量:
class /* ... */ {
private SQLiteDatabase db;
/* ... */
@Override
public void onCreate(Bundle savedInstanceState) {
/* ... */
db = repo.getWritableDatabase();
/* ... */
}
/* ... */
}