从Android中的素材资源文件夹中检索数据

时间:2018-08-16 13:17:40

标签: java android sqlite

我无法将资产文件夹中的数据库插入到我的主要活动中。运行此程序时出现错误。

我需要放置在该列中,并且该列在名称活动中。

public class DatabaseHelper extends SQLiteOpenHelper {

    private static String DB_PATH = "file:///android_asset/bcanew.db";
    private static String DB_NAME = "bcanew.db";
    private SQLiteDatabase myDataBase;
    private Context context;
    public static final String TABLE_NAME = "student_names";
    public static final String COL_1 = "ID";
    public static final String COL_2 = "NAME";
    public static final String COL_3 = "CURRENT_CGPA";
    public static final String COL_4 = "ACTIVE_BACKLOGS";

    public DatabaseHelper(Context context, Names names, SQLiteDatabase.CursorFactory factory, int version) {

        super(context, String.valueOf(names), factory, version);
    }

    private void copyDataBase() throws IOException {

        // Open your local db as the input stream
        InputStream myInput = context.getAssets().open(DB_NAME);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

        db = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
        onCreate(db);
    }

    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res;
        res = db.rawQuery("select * from " + TABLE_NAME, null);
        return res;
    }
}

2 个答案:

答案 0 :(得分:0)

您应该已经在与“ res”文件夹相同的目录中创建了“资产”文件夹。从路径的外观看来,您已经创建了一些自定义的其他目录。

在与“ res”文件夹相同的目录下创建资产文件夹。 然后调用以下方法:

getAssets().open("filename_in_assets_directory");

您可能需要做:

context.getAssets().open("filename_in_assets_directory");

如果您不是通过活动打来的电话。

答案 1 :(得分:0)

尝试此代码。 从资产文件夹读取文件的方法,然后将文件作为字符串返回。

private String readFile(String fileName, Context context) {
    StringBuilder returnString = new StringBuilder();
    InputStream fIn = null;
    InputStreamReader isr = null;
    BufferedReader input = null;
    try {
        fIn = context.getResources().getAssets().open(fileName);
        isr = new InputStreamReader(fIn);
        input = new BufferedReader(isr);
        String line;
        while ((line = input.readLine()) != null) {
            returnString.append(line);
        }
    } catch (Exception e) {
        e.getMessage();
    } finally {
        try {
            if (isr != null) isr.close();
            if (fIn != null) fIn.close();
            if (input != null) input.close();
        } catch (Exception e2) {
            e2.getMessage();
        }
    }
    return returnString.toString();
}

之后,像这样将方法调用为活动或片段。

        String jsonObject = readFile("wg_sample.json", this); // define file name here define one json file name.