我无法将资产文件夹中的数据库插入到我的主要活动中。当我运行这个时出现错误。
我需要放置在该列中,并且该列位于名称活动中。
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;
}
}
试试这个代码.. 创建从资产文件夹读取文件的方法..并将文件作为字符串返回。
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.
您应该在“res”文件夹所在的目录中创建一个“assets”文件夹。从路径的外观来看,您似乎已经创建了一些自定义的其他目录。
在“res”文件夹所在的目录下创建资产文件夹。 然后调用以下方法:
getAssets().open("filename_in_assets_directory");
你可能需要做:
context.getAssets().open("filename_in_assets_directory");
如果您不是在活动中致电。