android中使用putSerializable()方法的妙处

前段时间做项目时无意中乱用了putSerializable这个方法,结果达到了目的,这令我很惊讶,当时以为是这个方法有超越其他方法的奇效,当时的代码是这样写的:
这个是下一个页面的UpdateActivity中的查询方法:

     //findAll
public ArrayList<HashMap<String, Object>> findAll(){
//查询所有
Cursor c;
    c = db.rawQuery("select g.ID,g.GoodsID,g.GoodsName,g.SellerID,g.Price,g.Specification,g.Unit,s.ID,s.SellerExtraName from T_Goods as g inner join T_Seller as s on g.SellerID = s.ID", null);
TGoods gods=new TGoods();
ArrayList<HashMap<String, Object>> arrayList=new ArrayList<HashMap<String,Object>>();
while(c.moveToNext()){
HashMap<String,Object> map=new HashMap<String, Object>();
map.put("ID", c.getInt(c.getColumnIndex("ID")));
map.put("GoodsID", c.getString(c.getColumnIndex("GoodsID")));
map.put("GoodsName", c.getString(c.getColumnIndex("GoodsName")));
map.put("SellerExtraName", c.getString(c.getColumnIndex("SellerExtraName")));
map.put("Price", c.getFloat(c.getColumnIndex("Price")));
map.put("Specification", c.getString(c.getColumnIndex("Specification")));
map.put("Unit", c.getString(c.getColumnIndex("Unit")));
arrayList.add(map);
}
Bundle bundle=new Bundle();
bundle.putSerializable("arrayList", arrayList);
Intent intent=new Intent();
intent.setClass(UpdateActivity.this, SelTGoodsActivity.class);
startActivity(intent);
return arrayList;
}

这个是上一个SelActivity的查询页面的代码:

   //查询所有
Cursor c;
    c = db.rawQuery("select g.ID,g.GoodsID,g.GoodsName,g.Price,g.Specification,g.Unit,s.SellerExtraName from T_Goods as g inner join T_Seller as s on s.ID = g.SellerID", null);
ArrayList<HashMap<String, Object>> arrayList=new ArrayList<HashMap<String,Object>>();
while(c.moveToNext()){
HashMap<String,Object> map=new HashMap<String, Object>();
map.put("ID", c.getInt(c.getColumnIndex("ID")));
map.put("GoodsID", c.getString(c.getColumnIndex("GoodsID")));
map.put("GoodsName", c.getString(c.getColumnIndex("GoodsName")));
map.put("SellerExtraName", c.getString(c.getColumnIndex("SellerExtraName")));
map.put("Price", c.getString(c.getColumnIndex("Price")));
map.put("Specification", c.getString(c.getColumnIndex("Specification")));
map.put("Unit", c.getString(c.getColumnIndex("Unit")));
arrayList.add(map);
}
SimpleAdapter adapter=new SimpleAdapter(
this,
arrayList,
R.layout.selectlist,
new String[]{"GoodsID","GoodsName","SellerExtraName","Price","Specification","Unit"},
new int[]{R.id.goodsId,R.id.goodsName,R.id.prodctorName,R.id.price,R.id.guige,R.id.danwei});
selList.setAdapter(adapter);



    从这些代码中可以看出,虽然我在UpdateActivity中写了bundle.putSerializable("arrayList", arrayList);但是在SelActivity中我并没有写什么接收的getXXX()方法,但我的目的还是达到了,当时以为是putSerializable("arrayList", arrayList);这个方法有什么奇效,因为干项目进度就没有多看为什么,方才才发现原来是那个被意图传过来的arrayList在起作用,事实上是我们只需要在传递数据的Activity中把要传递的数据添加到这个方法中,都不要putExtras()就可以把数据传递到接收的Activity中,最重要的是前后那两个Activity中的“arrayList”必须是equals的,否则就不行,原理是这样的,UpdateActivity中的arrayList被传到SelActivity中时会自动的找有没有与它同样的变量,有的话就把值赋给那个变量,这样就传递了数据,我这里传递的是一个集合,而且里面还是map,其实也可以放对象等等。

猜你喜欢

转载自1397452815.iteye.com/blog/2145231