我正在使用放置在app资产文件夹中的外部sqlite数据库。我可以从这个数据库中读取数据,但我想在这个数据库中插入新的条目。 我知道内部数据库使用contentvalue是如此容易,但在外部数据库中如何做到这一点?
答案 0 :(得分:0)
首先,您需要将数据库复制到SD卡,然后使用以下类初始化数据库: -
public class DatabaseHandler extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private String mDBpath = "";
private String mDBpathactual = "";
private static String DB_NAME ="DKDB.sqlite";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DatabaseHandler(Context context , String db_path,String db_name,int db_ver)
{
super(context, db_name, null, db_ver);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 17){
mDBpath = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
mDBpath = "/data/data/" + context.getPackageName() + "/databases/";
}
DB_NAME = db_name;
mDBpathactual = db_path+db_name;
this.mContext = context;
// mDBpath = this.mContext.getDatabasePath(DB_NAME);
}
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist || mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(mDBpath + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
if(dbFile.exists())
dbFile.delete();
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = new FileInputStream(mDBpathactual);
String outFileName = mDBpath + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = mDBpath +DB_NAME ;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
@Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}