我有一个应用程序,可以将数据存储在数据库中。现在,我想要一个按钮将此数据库导出到文本文件中。
以下是我的导出按钮的代码:
//BUTTON ACTION
public void Save(View view) {
//Saving the data into the data base
SQLiteDatabase db = DataBase.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name.getText().toString());
values.put("phone", phone.getText().toString());
values.put("email", email.getText().toString());
values.put("job", job.getText().toString());
values.put("others", others.getText().toString());
long result= db.insert("table_customer", null, values);
Cursor cursor = db.query ("table_customer", new String[]{"name", "phone", "email", "job", "others"}, null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> customer = new HashMap<String, String>();
cliente.put("_id_customer", cursor.getString(cursor.getColumnIndex("_id_customer")));
cliente.put("name", cursor.getString(cursor.getColumnIndex("name")));
cliente.put("phone", cursor.getString(cursor.getColumnIndex("phone")));
cliente.put("email", cursor.getString(cursor.getColumnIndex("email")));
cliente.put("job", cursor.getString(cursor.getColumnIndex("job")));
cliente.put("others", cursor.getString(cursor.getColumnIndex("others")));
}
while (cursor.moveToNext());
}
cursor.close();
if (resultado != -1) {
Toast.makeText(this, "Customer saved and file exported", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Error 2", Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
您需要使用db
对象的方法查询数据库。然后,您需要迭代这些结果并将它们写入您的文件。在SQLiteDatabase文档中查看可用的方法。
编辑1:
尝试这样的事情:
Cursor cursor = db.query ("table_customer", new String[]{"name","phone", "email", "job", "others"},null,null,null,null,null);
//cursor is now at the first result returned by this query
do{
int colIdx = cursor.getColumnIndex("name");
String name = cursor.getString(colIdx);
//do something with name
}while(cursor.moveToNext()); //loop will terminate when all the rows are exhausted
编辑2: 这是一个link to an article,详细说明了如何使用查询和游标功能。
答案 1 :(得分:0)
您可以做的是依次使用select all查询查询每个表,并且对于每个表,使用StringBuilder手动构建XML或CSV(逗号分隔值)文件。
例如,如果Persons表具有以下列{ID,FNAME,LNAME,AGE},那么对于包含两行数据的表,我可以为XML生成以下内容
<persons>
<person>
<ID>1</ID>
<FNAME>Isaac</FNAME>
<LNAME>Meacock</LNAME>
<AGE>27</AGE>
</person>
<person>
<ID>2</ID>
<FNAMENorah</FNAME>
<LNAME>Bone</LNAME>
<AGE>52</AGE>
</person>
<persons>
或以下用于CSV
1, Isaac, Meacock, 27
2, Norah, Bone, 53
然后,只需用Java保存标准文本文件即可。