0
public void execSqlFromAssets(String path) {
    InputStream input;
    String text;
    try {
        input = mCtx.getAssets().open(path + ".txt");
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();
        text = new String(buffer);
        String[] inserts = text.split(";");
        // SQLiteDatabase db = mDb;
        for (String insert : inserts) {
            insert = insert;
            Log.w(TAG, insert);
            try {
                mDb.execSQL(insert);
            } catch (Exception e) {
                String err = (e.getMessage() == null) ? "Cant execute sql"
                        + insert : e.getMessage();
                Log.w(TAG, err);
            }
        }

    } catch (IOException e) {
        Log.w(TAG, "execSqlFromAssets: " + path + " file not found");
    }

}

这是我的代码问题在线包含mDb.execSQL(insert)。它抛出我无法读取的异常值为空。我只是不明白其中一条错误消息是: Cant execute sqlINSERT INTO food (name, cals) VALUES ("kolac",270)。任何帮助表示赞赏

4

1 回答 1

0

好的,@Preet Sangha 要求我发布解决方案。我的问题是我在 onCreate 方法的 SQLiteOpenHelper 实例中调用了这个函数,而 mDb 实例还没有创建,所以我将函数更改为这个

public void execSqlFromAssets(String path, SQLiteDatabase db) {
    if(db == null){
        db = mDb;
    }
    InputStream input;
    String text;
    try {
        input = mCtx.getAssets().open(path + ".txt");
        int size = input.available();
        byte[] buffer = new byte[size];
        input.read(buffer);
        input.close();
        text = new String(buffer);
        String[] inserts = text.split(";");
        for (String insert : inserts) {
            try {
                db.execSQL(insert);
            } catch (Exception e) {
                String err = (e.getMessage() == null) ? "Cant execute sql"
                        + insert : e.getMessage();
                Log.w(TAG, err);
            }
        }

    } catch (IOException e) {
        Log.w(TAG, "execSqlFromAssets: " + path + " file not found");
    }

}

所以现在如果我从 onCreate 调用这个函数,我会发送 db 作为第二个参数,如果我从应用程序的其他组件调用它,我会发送 null 作为第二个参数

于 2012-04-28T09:47:23.610 回答