【发布时间】:2017-04-23 18:22:52
【问题描述】:
我在我的应用中实现了一个 SQLite 表,现在想将它导出到设备本身。
我遵循了与此非常相似的代码: Where exported CSV file is saved?
还有这个: http://paragchauhan2010.blogspot.co.uk/2012/08/database-table-export-to-csv-in-android.html
然而,无论我如何修改,CSV 文件都不会显示在我的设备上。我没有安装 sd 卡,但由于现在模拟了外部存储,所以应该没关系吧?
导出方式:
private void exportDB() {
File dbFile = getDatabasePath("emotionSQLTable.db");
EmotionListDbHelper dbhelper = new EmotionListDbHelper(getApplicationContext());
//switching out to internal directory here, for debu purposes and because we dont have sd card
final String appPath = String.format
(
"%s/Aletheia", Environment.getExternalStorageDirectory()
);
File exportDir = new File(appPath);
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName = new SimpleDateFormat("yyyyMMddHHmm").format(new Date());
//TODO for debugging purposes
File file = new File(exportDir, "emotionSQLTable.csv");
try {
file.createNewFile();
CSVWriter csvWrite = new CSVWriter(new FileWriter(file));
SQLiteDatabase db = dbhelper.getReadableDatabase();
//Here we select from the TABLE NAME, which is emotionlist
Cursor curCSV = db.rawQuery("SELECT * FROM emotionlist", null);
csvWrite.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
//Which column you want to exprort
String arrStr[] = {curCSV.getString(0), curCSV.getString(1), curCSV.getString(2)};
csvWrite.writeNext(arrStr);
}
csvWrite.close();
curCSV.close();
} catch (Exception sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
DBHelper 类
public class EmotionListDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "emotionSQLTable.db";
private static final int DATABASE_VERSION = 1;
public EmotionListDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String SQL_CREATE_WAITLIST_TABLE = "CREATE TABLE emotionlist(_id INTEGER PRIMARY KEY AUTOINCREMENT, anger DOUBLE NOT NULL, contempt DOUBLE NOT NULL, disgust DOUBLE NOT NULL, fear DOUBLE NOT NULL, happiness DOUBLE NOT NULL, neutral DOUBLE NOT NULL, sadness DOUBLE NOT NULL, surprise DOUBLE NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP);";
sqLiteDatabase.execSQL("CREATE TABLE emotionlist(_id INTEGER PRIMARY KEY AUTOINCREMENT, anger DOUBLE NOT NULL, contempt DOUBLE NOT NULL, disgust DOUBLE NOT NULL, fear DOUBLE NOT NULL, happiness DOUBLE NOT NULL, neutral DOUBLE NOT NULL, sadness DOUBLE NOT NULL, surprise DOUBLE NOT NULL, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP);");
}
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS emotionlist");
onCreate(sqLiteDatabase);
}
到目前为止,我已经尝试将代码移动到 AsyncTask 中,将其存储在内部存储器中,但无济于事。任何建议将不胜感激
【问题讨论】:
标签: android database sqlite csv export-to-csv