我开发了一个应用程序,我将数据库从assets文件夹复制到我的硬编码路径.所以日食给了我警告:
Do not hardcode "/data/"; use Context.getFilesDir().getPath() instead
我在谷歌搜索并找到答案使用:
Context.getFilesDir().getPath();
并且硬编码不适用于每个设备,有些可能会出错或无法正常工作.但通过实施上述我得到错误.
我的代码如下:
private final Context myContext;
在这里得到警告
private static String DB_PATH = "/data/data/com.example.abc/databases/"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "exampledb.sqlite"; static SQLiteDatabase sqliteDataBase; public DataBaseHelperClass(Context context) { super(context, DATABASE_NAME, null ,DATABASE_VERSION); this.myContext = context; } public void createDataBase() throws IOException{ boolean databaseExist = checkDataBase(); if(databaseExist){ this.getWritableDatabase(); }else{ this.getReadableDatabase(); copyDataBase(); } } public boolean checkDataBase(){ File databaseFile = new File(DB_PATH + DATABASE_NAME); return databaseFile.exists(); } private void copyDataBase() throws IOException{ InputStream myInput = myContext.getAssets().open(DATABASE_NAME); String outFileName = DB_PATH + DATABASE_NAME; OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer))>0){ myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); } public void openDataBase() throws SQLException{ String myPath = DB_PATH + DATABASE_NAME; sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } @Override public synchronized void close() { if(sqliteDataBase != null) sqliteDataBase.close(); super.close(); } public Cursor myFunction(){ } @Override public void onCreate(SQLiteDatabase db) {} @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
请告诉我如何解决警告的方法.
日食给你的提示不够好.
您可以获取数据库路径context.getDatabasePath();
您应该将所需的名称传递给文件(无论是否存在),在您的情况下exampledb.sqlite
所以你的代码将是:
File outFile =myContext.getDatabasePath(DATABASE_NAME); String outFileName =outFile.getPath() ;
当然,myContext
必须是当前的背景.例如,这是调用它的运行活动或服务.
做如下:
public DataBaseHelperClass(Context context) { super(context, DATABASE_NAME, null ,DATABASE_VERSION); this.myContext = context; //The Android's default system path of your application database. DB_PATH = myContext.getDatabasePath(DATABASE_NAME).getPath(); }
你不会得到错误或警告.