如何在sdcard中存储Android SQLite数据库

我刚刚创建了数据库,它默认存储在data / data / database文件夹中。现在我想在sdcard中存储数据库,我使用了以下代码。请指示我必须在哪里添加代码。谢谢

码:

public class DataBaseHandler { SQLiteDatabase database; private static DataBaseHandler obj; private final String TABLE_NAME = "main_db"; private final String COLUMN_FIRST = "_id"; MovieDetails md = new MovieDetails(); private DataBaseHandler(Context context) { DataBase dbobj = new DataBase(context, "Id_db.db", null, 1); database = dbobj.getWritableDatabase(); } public static DataBaseHandler getinstance(Context context) { if (obj == null) { obj = new DataBaseHandler(context); } return obj; } public void insertData(String id) { try { ContentValues values = new ContentValues(); values.put(COLUMN_FIRST, id); database.insert(TABLE_NAME, null, values); } catch (Exception er) { Log.d("Error is===", er.toString()); } } public void deleteData(String id) { database.delete(TABLE_NAME, BaseColumns._ID + "=" + id, null); } public Cursor getData() { String[] columns = { BaseColumns._ID, COLUMN_FIRST }; return database .query(TABLE_NAME, columns, null, null, null, null, null); } private class DataBase extends SQLiteOpenHelper { public DataBase(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + "(" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_FIRST + " varchar(50)NOT NULL UNIQUE);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } } 

使用此类复制数据库:

 public class MyDatabaseTools { private String appName = ""; private String packageName = ""; public boolean backup() { boolean rc = false; boolean writeable = isSDCardWriteable(); if (writeable) { File file = new File(Environment.getDataDirectory() + "/data/" + packageName + "/databases/" + MySQLiteOpenHelper.getDatabaseName()); File fileBackupDir = new File(Environment.getExternalStorageDirectory(), appName + "/backup"); if (!fileBackupDir.exists()) { fileBackupDir.mkdirs(); } if (file.exists()) { File fileBackup = new File(fileBackupDir, MySQLiteOpenHelper.getDatabaseName()); try { fileBackup.createNewFile(); FileUtils.copyFile(file, fileBackup); rc = true; } catch (IOException ioException) { // } catch (Exception exception) { // } } } return rc; } private boolean isSDCardWriteable() { boolean rc = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { rc = true; } return rc; } public MyDatabaseTools(final Context context, final String appName) { this.appName = appName; packageName = context.getPackageName(); } } 

如果您不了解如何使用它,请参阅来源 。