我正在尝试从我的数据库中获取某些字段到PDF的报告。 pdf正在生成完美但它只是从数据库中读取第一个条目而不是所有条目。
这是我的PDF代码:
public void exportDataBaseIntoPDF() {
Document doc = new Document(PageSize.A4);
try {
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MSS Jobsheets";
date = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.d("PDFCreator", "PDF Path: " + path);
filePDF = new File(dir, "Report" + "(" + date + ")" + ".pdf");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(filePDF);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
PdfWriter.getInstance(doc, fOut);
doc.open();
DBHelper db = new DBHelper(this);
Cursor cursor = db.getDataItem();
int count = cursor.getCount();
cursor.moveToFirst();
for (int j = 0; j < count; j++) {
PdfPTable table = new PdfPTable(2);
table.addCell(cursor.getString(cursor.getColumnIndex("name")));
table.addCell(cursor.getString(cursor.getColumnIndex("gender")));
cursor.moveToNext();
doc.add(table);
doc.close();
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
这是从我的DBHelper类中提取数据:
public Cursor getDataItem() {
SQLiteDatabase db = this.getReadableDatabase();
String q = "SELECT * FROM " + PERSON_TABLE_NAME;
Cursor mCursor = db.rawQuery(q, null);
return mCursor;
}
}
但就像我说的那样,它只读取数据库中的第一行并添加数据,但不会移动到数据库中的下一行以在PDF中添加数据。
有人可以帮我解决这个问题吗? 提前谢谢!
答案 0 :(得分:1)
实际问题与游标无关,光标读取下一行但在第一次数据写入后关闭文档。尝试关闭for循环之外的文档对象。
将此行放在for loop
doc.close();