我已经创建了一个SQLite数据库。我想在我的Android项目中使用这个数据库文件。我想将这个数据库与我的应用程序捆绑在一起。
应用程序如何访问此数据库并将其用作其数据库,而不是创建一个新数据库?
发布于 2012-12-13 01:15:32
关于这个问题,我在其他DatabaseHelpers上遇到了麻烦,不知道为什么。
这是对我有效的方法:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = DatabaseHelper.class.getSimpleName();
private final Context context;
private final String assetPath;
private final String dbPath;
public DatabaseHelper(Context context, String dbName, String assetPath)
throws IOException {
super(context, dbName, null, 1);
this.context = context;
this.assetPath = assetPath;
this.dbPath = "/data/data/"
+ context.getApplicationContext().getPackageName() + "/databases/"
+ dbName;
checkExists();
}
/**
* Checks if the database asset needs to be copied and if so copies it to the
* default location.
*
* @throws IOException
*/
private void checkExists() throws IOException {
Log.i(TAG, "checkExists()");
File dbFile = new File(dbPath);
if (!dbFile.exists()) {
Log.i(TAG, "creating database..");
dbFile.getParentFile().mkdirs();
copyStream(context.getAssets().open(assetPath), new FileOutputStream(
dbFile));
Log.i(TAG, assetPath + " has been copied to " + dbFile.getAbsolutePath());
}
}
private void copyStream(InputStream is, OutputStream os) throws IOException {
byte buf[] = new byte[1024];
int c = 0;
while (true) {
c = is.read(buf);
if (c == -1)
break;
os.write(buf, 0, c);
}
is.close();
os.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
发布于 2012-02-02 17:03:19
您可以通过使用content provider来完成此操作。应用程序中使用的每个数据项对应用程序来说都是私有的。如果应用程序想要跨应用程序共享数据,则只有一种技术可以实现这一点,即使用提供访问私有数据接口的内容提供商。
https://stackoverflow.com/questions/9109438
复制相似问题