循环外定义变量 tempReportInfo
public ArrayList<ReportInfo> getAllReportInfos() {
ArrayList<ReportInfo> reportInfos = new ArrayList<ReportInfo>();
Cursor cursor = null;
ReportInfo tempReportInfo = new ReportInfo();
synchronized (helper) {
if (!db.isOpen()) {
db = helper.getWritableDatabase();
}
cursor = db.rawQuery("SELECT * FROM " + DBKeysName.TABLE_REPORT,
null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
tempReportInfo.setUserIds(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_USERID)));
tempReportInfo
.setStationName(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_STATIONNAME)));
tempReportInfo.setTime(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_TIME)));
tempReportInfo.setLineId(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_LINEID)));
tempReportInfo.setType(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_TYPE)));
tempReportInfo.setRole(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_ROLE)));
tempReportInfo.setFlag(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_FLAG)));
reportInfos.add(tempReportInfo);
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
cursor.close();
}
}
return reportInfos;
}
上述例子得到的结果是,reportInfos添加的是数量为与数据表里行数一样的,但内容为数据表里第一条数据.
循环内定义变量tempReportInfo
public ArrayList<ReportInfo> getAllReportInfos() {
ArrayList<ReportInfo> reportInfos = new ArrayList<ReportInfo>();
Cursor cursor = null;
synchronized (helper) {
if (!db.isOpen()) {
db = helper.getWritableDatabase();
}
cursor = db.rawQuery("SELECT * FROM " + DBKeysName.TABLE_REPORT,
null);
try {
if (cursor != null) {
while (cursor.moveToNext()) {
ReportInfo tempReportInfo = new ReportInfo();
tempReportInfo.setUserIds(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_USERID)));
tempReportInfo
.setStationName(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_STATIONNAME)));
tempReportInfo.setTime(cursor.getString(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_TIME)));
tempReportInfo.setLineId(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_LINEID)));
tempReportInfo.setType(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_TYPE)));
tempReportInfo.setRole(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_ROLE)));
tempReportInfo.setFlag(cursor.getInt(cursor
.getColumnIndex(DBKeysName.ROW_REPORT_FLAG)));
reportInfos.add(tempReportInfo);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
cursor.close();
}
}
return reportInfos;
}
这样才能得到想要的结果:reportInfos添加了数据表里的所有数据.
请问一下,为什么循环外定义变量tempReportInfo就得到不一样的结果呢?