android - 无法从 Android 中的本地 SQLite 数据库读取?

标签 android database sqlite

您好,我在读取项目中的嵌入式 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/

相关文章:

java - 使用retrofit2上传后获取带有 "0 bytes on disk"的文件

java - Android Studio 给了我 BuildConfig 错误

java - 具有唯一键约束的android sqliteDatabase表创建不会为重复条目抛出异常

sql - 数据库,其他语言的列名

mysql - 在 rails sqlite vs mysql 中随机选择

android - 如何使用volley从android上传用户指定数量的图像或文档?

java - 如何在 android 中解决 java.lang.IndexOutOfBoundsException?

database - 函数依赖的规范覆盖

sqlite - 如何按列组计算百分比

node.js - Electron-rebuild 构建错误版本的 node-sqlite3