Android学习笔记之View大集合(个人笔记)
如图,做一个小签到程序,在第一个Activity中填入签到信息。然后在第二个Activity中显示出来。
可以看到,这个程序涉及到TextView、EditText、Spinner、RadioGroup、RadioButton、Button、ListView组件,可以练习一下View 的使用方法。我的思路是创建一个个人信息类PersonInfo,在点击签到按钮后生成一个PersonInfo对象,并将对象传入第二个Activity中,在第二个Avctivity中用一个PersonInfo来存储接受到的对象,再显示出来。
问题一:Activity中Intent传递对象的方法,为此参考了此文中谈到的两种方法:1、实现了Serializable接口;2、实现了Parcelable接口。
过程还是蛮顺利,成功的接收到了PersonInfo对象。然后工作就是在ListActivity中展示出来,我的代码是这么写的
package com.zxl.signin; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.os.Bundle; import android.widget.SimpleAdapter; public class InfoListActivity extends ListActivity { private Bundle bundle; private PersonInfo[] personInfos; private SimpleAdapter lisAdapter; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //获得从上一个activity中传入的person对象 personInfos = new PersonInfo[10]; getPerson(); setAdaptet(); } private void getPerson() { bundle = getIntent().getExtras(); PersonInfo person = (PersonInfo) bundle.getSerializable("info"); int i = person.getId(); personInfos[i] = person; System.out.println(i); } private void setAdaptet() { ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>(); for (int i = 1; i <= PersonInfo.no; i++) { HashMap<String, String> map = new HashMap<String, String>(); map.put("name", personInfos[i].getName()); map.put("school", personInfos[i].getSchool()); map.put("sex", personInfos[i].getSex()); map.put("tel", personInfos[i].getTelNo()); list.add(map); } lisAdapter = new SimpleAdapter(this, list, R.layout.listitem, new String[] {"name", "school", "sex", "tel"}, new int[] {R.id.name, R.id.school, R.id.sex, R.id.tel}); setListAdapter(lisAdapter); } }
看似并无问题,没注册一个Person就往数组personInfos里放,然后在setAdapter中用一个循环从数组中取出并显示在ListActivity中。
显示挺正常的,但是当我按下返回键退出到Activity中后,再次注册的话会报空指针异常。DeBug了好久,终于发现疏忽了。原来ListAcitivity在按返回键后其中的数组personInfos并没有存储,再次点击注册后会重新new一个personInfos,这就导致for循环时会报错,因为personInfos[1]=null。
头疼了,那临时存储这个personInfos该怎么存?还没有想到解决办法。