循環外定義變量 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就得到不一樣的結果呢?
放外面也行
但是需要每次循環都加上
tempReportInfo = new ReportInfo();
否則只創建了一個對象,你修改來修改去,添加到集合的都是指向同一個對象的引用