Exporting a SQLite database to an XML file in Android
I know this is possible bu开发者_StackOverflowt I'm not really sure where to start. Has anyone been able to achieve this?
Thanks.
The DataXmlExporter
class described in this article will export a SQL lite DB to an XML file.
http://www.screaming-penguin.com/node/7749
The full example is available in this SVN repo. The ManageData
class invokes the export.
http://totsp.com/svn/repo/AndroidExamples/trunk/
You will need to create an application class that exposes the DB and referenced as the application name in the AndroidManifest.xml file. Then use that DB as the argument to the DataXmlExporter
constructor.
Here's the application class I use. You should already have a class (probably not named DatabaseHelper
) that extends SQLiteOpenHelper
package com.billybobbain.android.someapp;
import android.app.Application;
import android.util.Log;
public class MyApplication extends Application {
public static final String APP_NAME = "SomeApp";
private DatabaseHelper dataHelper;
@Override
public void onCreate() {
super.onCreate();
Log.d(APP_NAME, "APPLICATION onCreate");
this.dataHelper = new DatabaseHelper(this);
}
@Override
public void onTerminate() {
Log.d(APP_NAME, "APPLICATION onTerminate");
super.onTerminate();
}
public DatabaseHelper getDataHelper() {
return this.dataHelper;
}
public void setDataHelper(DatabaseHelper dataHelper) {
this.dataHelper = dataHelper;
}
}
Have a look at the source code here exporting-a-sqlite-database-to-an-xml-file-in-android
The only change I had to make (to stop a few Eclipse warnings) was to close a cursor in the exportData( ) method. To make the code more portable, I also passed the XML file and location as an argument rather then as a declared final field.
The code writes the XML file to the SD card. Now, @mmaitlen who listed the source code on his blog doesn't add in any features to test for the existence of an external storage unit. So that's left for you to do.
However, you can embed some simple code to test for the existence of a writeable memory card with the following snippet (untested):
sdOkToWrite = false;
String sdTest = Environment.getExternalStorageState();
if (sdTest.equals(Environment.MEDIA_MOUNTED)) {
sdOkToWrite = true;
} else {
// Here's where you can code what to do without the external storage
}
Testing for the external storage is useful if you have large files to create that may exceed internal capacity.
I found this very helpful:
http://www.phonesdevelopers.com/1788273/
Using it the following way to export it to the sd card:
File sd = Environment.getExternalStorageDirectory();
String path = sd + "/" + DB_NAME + ".xml";
DatabaseDump databaseDump = new DatabaseDump(mySQLiteOpenHelperObject.getReadableDatabase(), path);
databaseDump.exportData();
Of course don't forget:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
精彩评论