SQLiteOpenHelper 在公用文件夹中具有完全限定的 DB 路径 namedatabse

通常,Android-SQLiteOpenHelper 不允许存储数据库的完全限定路径名。因此无法使用公共数据库文件。

如果提供自定义 ContextClass 并且在目标目录中具有写访问权限,则可以将 SQLiteOpenHelper 与自定义路径一起使用。

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 3;
    .....

    DatabaseHelper(final Context context, String databaseName) 
    {
       super(new DatabaseContext(context), databaseName, null, DATABASE_VERSION);
    }
}

这是自定义 DatabaseContext 类,可以完成所有的魔术

class DatabaseContext extends ContextWrapper {

    private static final String DEBUG_CONTEXT = "DatabaseContext";

    public DatabaseContext(Context base) {
        super(base);
    }

    @Override
    public File getDatabasePath(String name) 
    {
        File sdcard = Environment.getExternalStorageDirectory();    
        String dbfile = sdcard.getAbsolutePath() + File.separator+ "databases" + File.separator + name;
        if (!dbfile.endsWith(".db"))
        {
            dbfile += ".db" ;
        }

        File result = new File(dbfile);

        if (!result.getParentFile().exists())
        {
            result.getParentFile().mkdirs();
        }

        if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN))
        {
            Log.w(DEBUG_CONTEXT,
                    "getDatabasePath(" + name + ") = " + result.getAbsolutePath());
        }

        return result;
    }

    /* this version is called for android devices >= api-11. thank to @damccull for fixing this. */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
        return openOrCreateDatabase(name,mode, factory);
    }

    /* this version is called for android devices < api-11 */
    @Override
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) 
    {
        SQLiteDatabase result = SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
        // SQLiteDatabase result = super.openOrCreateDatabase(name, mode, factory);
        if (Log.isLoggable(DEBUG_CONTEXT, Log.WARN))
        {
            Log.w(DEBUG_CONTEXT,
                    "openOrCreateDatabase(" + name + ",,) = " + result.getPath());
        }
        return result;
    }
}

这是我对 SQLiteOpenHelper 问题的回答的副本,其中包含完全限定的 DB 路径名