将数据库从资产文件夹导出到应用程序并替换空数据库

时间:2015-04-13 07:19:22

标签: android database android-sqlite osmdroid



在[模拟器] [DDMS]中 当我将数据库manualy放在data / data / mypackage / databases /中时,它运行顺畅。

[Android设备]

当我导出到apk文件并安装到Android设备。 应用程序将强制关闭。 当我检查android设备中的文件夹路径data / data / myPackage / databases /中有空数据库时,我不知道它来自哪里。当我删除该空数据库并替换为我现有的数据库。应用程序顺利运行。

问题是,如何在资产文件夹中替换数据库[有数据]并用资产文件夹中的数据库[有数据]替换空数据库创建自己。

在我的编码下面,如果我有错误请告诉我

谢谢谁回复我, 关于Hafizul Reza

public class MainActivity extends Activity {

ArrayList<OverlayItem> anotherOverlayItemArray;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MapView mapView = new MapView(this, 256);
setContentView(R.layout.activity_main);
 mapView.setClickable(true);
 mapView.setMultiTouchControls(true);
 mapView.setBuiltInZoomControls(true);

setContentView(mapView);
mapView.getController().setZoom(4);
mapView.getController().setCenter(new GeoPoint(4.415895,101.383082));
mapView.setUseDataConnection(false);
mapView.setTileSource(TileSourceFactory.MAPQUESTOSM);

SQLiteDatabase myDB = null;
String TableName = "Landslide";

 myDB = this.openOrCreateDatabase("Landslide.sqlite", MODE_PRIVATE, null);
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName, null);
 if (c != null) {
if (c.moveToFirst()) {
do {
Double lat = c.getDouble(c.getColumnIndex("Latitude"));
Double lng = c.getDouble(c.getColumnIndex("Longitude"));

anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem(
                "Ringlet", "Cameron Highland", new GeoPoint(lat, lng)));

ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay 
            = new ItemizedIconOverlay<OverlayItem>(this, anotherOverlayItemArray, null);

mapView.getOverlays().add(anotherItemizedIconOverlay);
} while (c.moveToNext());
}
}

2 个答案:

答案 0 :(得分:1)

检查这些行 myDB = this.openOrCreateDatabase(&#34; Landslide.sqlite&#34;,MODE_PRIVATE,null); 游标c = myDB.rawQuery(&#34; SELECT * FROM&#34; + TableName,null);

在第一行,您正在尝试打开数据库。如果它不存在,它将创建一个新的,它将返回该数据库实例。(空数据库) 你的下一行令人困惑。您正在查询数据库。但我没有看到任何代码添加或插入任何行。你能分享一下有关崩溃的更多信息吗?

答案 1 :(得分:0)

使用此代码将数据库从资产文件夹复制到app文件夹:

private void copy(String file, String folder) throws IOException {
    File CheckDirectory;
    CheckDirectory = new File(folder);

    String parentPath = CheckDirectory.getParent();
    File filedir = new File(parentPath);
    if (!filedir.exists()) {
        if (!filedir.mkdirs()) {
            return;
        }
    }           
    InputStream in = this.getApplicationContext().getAssets().open(file);
    File newfile = new File(folder);
    OutputStream out = new FileOutputStream(newfile);

    byte[] buf = new byte[1024];
    int len; while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close(); out.close();
}

文件是您的数据库名称,文件夹是您要复制它的位置