循环外定义变量 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();
否则只创建了一个对象,你修改来修改去,添加到集合的都是指向同一个对象的引用
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。