寫基類的APP類,用于承接上下文
public classAppextendsApplication {
public staticAppappcontext;
@Override
public voidonCreate() {
super.onCreate();
appcontext=this;
}
}
建一個工具類
//加上Static 代表只運(yùn)行一次,且只復(fù)制一次數(shù)據(jù)庫
static{ copyDB(); }
public static voidcopyDB() {
InputStream input =null;
FileOutputStream output =null;
try{
input = App.appcontext.getAssets().open("db/commonnum.db");
File file =newFile(DB_PATH);
if(!file.exists()) file.mkdirs();
output =newFileOutputStream(DB_PATH+ File.separator+DB_NAME);
intlen =0;
byte[] buffer =new byte[1024];
while((len = input.read(buffer)) != -1) {
output.write(buffer,0,len);
}
}catch(IOException e) {
e.printStackTrace();
}finally{
try{
if(output !=null) output.close();
if(input !=null) input.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
舉一個例子
/**
* 獲取所有的服務(wù)類型的名字
*
* @return
*/
public static List<Tel> getTelServiceName() {
List<Tel> tels = new ArrayList<>();
//獲取數(shù)據(jù)庫
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(DB_PATH + "/" + DB_NAME, null);
//那個要查詢的數(shù)據(jù)庫的名字
Cursor cursor = db.rawQuery("select * from classlist;", null);
while (cursor.moveToNext()) {
//重?cái)?shù)據(jù)庫查詢名字
String name = cursor.getString(cursor.getColumnIndex("name"));
//從數(shù)據(jù)庫找到對應(yīng)的ID
int id = cursor.getInt(cursor.getColumnIndex("idx"));
//自己的一個實(shí)例類
Tel tel = new Tel(name, id);
//添加到集合中
tels.add(tel);
}
//關(guān)閉流,節(jié)省資源
cursor.close();
return tels;
}