您好,我在读取项目中的嵌入式 SQLite 数据库时遇到问题。
我想从一个 Activity 获取数据到另一个 Activity 并将其显示在 TextView 中。
这是我的数据库工具类:
public class myDBTools extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.appscan5/databases/";
private static String DB_NAME = "productlist";
private static SQLiteDatabase myDatabase;
public myDBTools(Context applicationContext) {
super(applicationContext, DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
myDatabase= SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,null, SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public static HashMap<String, String> getProductInfo(String id) {
HashMap<String, String> productMap = new HashMap<String, String>();
String selectQuery = "SELECT * FROM products WHERE _id='" + id + "'";
Cursor cursor = myDatabase.rawQuery(selectQuery, null);
// move to the first row of dataBase
if (cursor.moveToFirst()) {
do {
productMap.put("NumberId", cursor.getString(0));
productMap.put("BarcodeId", cursor.getString(1));
productMap.put("ProductName", cursor.getString(2));
productMap.put("Calories", cursor.getString(3));
productMap.put("Protein", cursor.getString(4));
productMap.put("Carbohydrates", cursor.getString(5));
productMap.put("Fats", cursor.getString(6));
productMap.put("Grams", cursor.getString(7));
} while (cursor.moveToNext());
}
return productMap;
}
}
这是我在另一个 Activity 中使用它的方式:
myDBTools mydbTools = new myDBTools(this);
HashMap<String, String> productMap = mydbTools.getProductInfo(id);
最佳答案
您需要先打开数据库。
mydbTools.open();
把上面一行放到你的oncreate中,它就会工作
关于android - 无法从 Android 中的本地 SQLite 数据库读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21767293/