当前位置: 代码迷 >> Android >> 数据库初始化,该怎么解决
  详细解决方案

数据库初始化,该怎么解决

热度:34   发布时间:2016-05-01 10:49:19.0
数据库初始化
public SQLiteDatabase initdatabase() {
// TODO Auto-generated method stub
if (!new File(databasepath).exists()) {

new File(databasepath).mkdir();
}

File databasefile = new File(databasepath + databasename);
if (!databasefile.exists()) {

try {
System.out.println(databasepath);
databasefile.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = activity.getResources().getAssets()
.open(databasename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
outputStream = new FileOutputStream(databasepath + databasename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}

byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
buffer = new byte[1024];// 一次写入128B的数据
System.out.println("write over!");
}
} catch (IOException e) {
e.printStackTrace();
}
// Close the streams
try {
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
sqLiteDatabase = null;
sqLiteDatabase = SQLiteDatabase.openDatabase(databasepath
+ databasename, null, SQLiteDatabase.OPEN_READWRITE);
Toast.makeText(activity, "位于本地的数据库初始化完成!", Toast.LENGTH_LONG)
.show();

}
sqLiteDatabase = SQLiteDatabase.openDatabase(databasepath
+ databasename, null, SQLiteDatabase.OPEN_READWRITE);

return sqLiteDatabase;

}


为什么一个初始化的代码要那么长? 哪些是可以省略的?
数据库

------解决方案--------------------
引用:
引用:public SQLiteDatabase initdatabase() throw Exception 
然后把trycatch删掉。
能给我一个删除之后的代码吗?谢谢啦



public SQLiteDatabase initdatabase() throws Exception {
        if (!new File(databasepath).exists()) {

            new File(databasepath).mkdir();
        }
        File databasefile = new File(databasepath + databasename);
        if (!databasefile.exists()) {
            System.out.println(databasepath);
            databasefile.createNewFile();
  相关解决方案