我开发了一个应用程序,在该应用程序中,我将数据库从assets文件夹复制到硬编码的路径中。所以eclipse给了我警告:
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();
}
您不会收到错误或警告。
只需使用活动/应用程序的上下文来获取路径,如:
Context c = getApplicationContext();
c.getFilesDir().getPath();