假设在我手机的内存中我有一个名为kc的文件夹,在那个kc文件夹中我有一个名为local.db的sqlite bd,现在我需要通过我的应用程序连接到该数据库,并且需要运行像select name这样的查询来自survey_master向我展示了主要活动onCreate方法的吐司结果。我怎么能这样做?
答案 0 :(得分:0)
创建数据库并将其命名为 myDB.sqlite 并将其放入您的app资源文件夹。
DB-Manager类
public class AppsDatabaseManager extends SQLiteOpenHelper{
public static final int VERSION = 1;
private String DB_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/yourFolderName";
private static String DB_NAME = "myDB.sqlite";
private SQLiteDatabase db;
private Context context;
public AppsDatabaseManager(Context context) {
super(context, DB_NAME, null, VERSION);
this.context = context;
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
}
public boolean initializeDatabase() {
if (DB_PATH == null)
return false;
try {
db = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null,
SQLiteDatabase.OPEN_READWRITE
| SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = context.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + "/" + DB_NAME;
// Open the empty db as the output stream
new File(outFileName).createNewFile();
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
}
在您的活动中:
AppsDatabaseManager dbManager = new AppsDatabaseManager(this);
if( dbManager.initializeDatabase() ){
//
}
在宣言中提供权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
下载我的完整示例:GitRepo