刻骨铭心的startActivityForResult三级跳获得第三个Activity中返回的数据
本文是为了记录开发过程中个人遇到的问题:
通过在第一个FirstActivity点击一个按钮用startActivityForResult启动第二个ProvincesActivity;显示的是一系列省份选择ListView,然后点击选择一个省份通过startActivityForResult启动第三个CityActivity,显示的是一系列之前所选省份下的城市;再通过选择其中一个城市返回给第一个FirstActivity!
public class FirstActivity extends Activity implements OnClickListener {
public final static int REQUEST_EVENT_CITY = 2;
public final static int REQUEST_EVENT_PROVINCES = 1;
public static final String ACTION_CHOOSE_CITY = "com.demo.CityActivity";
public static final String EXTRA_CHOOSE_CITY = "City";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
ProvincesActivity.actionFilterDataLaunch(this);//这是调用startActivityForResult方法
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {//在这里接收返回最后最后所选择的城市
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle bundle = data.getExtras();
String City = bundle
.getString(EXTRA_CHOOSE_CITY);
Log.i("Your choose city are", "*******************:" + City);
}
Log.i("TAG","***********************************" + data);
}
}
其中要注意的是在第二个ProvincesActivity中
public class ProvincesActivity extends Activity implements OnClickListener,
OnItemClickListener {
private String file1 = "province.xml"; // 文件名字
private LayoutInflater mInflater = null;
private TextView titleView;
private Button backButton;
private Button optionButton;
private ListView lvProvinces;
private ArrayList<String> mProviencesData = null;
private ProvincesAdapter adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.provinces_view);
initlayout();
}
public static void actionFilterDataLaunch(Context context) {
Intent i = new Intent(context, ProvincesActivity.class);
((Activity) context).startActivityForResult(i,
FirstActivity.REQUEST_EVENT_PROVINCES);
}
public void initlayout() {
mInflater = (LayoutInflater) this
.getSystemService(LAYOUT_INFLATER_SERVICE);
titleView = (TextView) findViewById(R.id.common_title_text);
backButton = (Button) findViewById(R.id.common_title_back);
optionButton = (Button) findViewById(R.id.common_title_option);
optionButton.setVisibility(View.INVISIBLE);
backButton.setOnClickListener(this);
titleView.setText("选择城市");
addDataToUI();
lvProvinces = (ListView) this.findViewById(R.id.lv_provinces);
adapter = new ProvincesAdapter();
lvProvinces.setAdapter(adapter); //设置适配器
lvProvinces.setOnItemClickListener(this); //设置Item响应监听
}
public void addDataToUI() {
mProviencesData =Util.parseXML(Util.getFromAsset(file1, this));//这是通过读取assets文件夹下得xml文件,再解析赋给ListView中的数组
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.common_title_back) {
finish();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (position >= 0) {
String Province = mProviencesData.get(position);
if (mProviencesData != null && mProviencesData.size() > 0) {
CityActivity.actionLaunch(this,Province);
//finish(); 特别注意不能在此finish这个ProvincesActivity (否则就等于切断了跳转的筋脉)
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (resultCode == RESULT_OK){
Bundle b = data.getExtras();
String city = b.getString(FirstActivity.EXTRA_CHOOSE_CITY);
Log.i("TAG", "*******************************"+city);
this.setResult(RESULT_OK, data); //就是在这里把返回所选择的城市setResult给FirstActivity
}
super.onActivityResult(requestCode, resultCode, data);
finish(); //finish应该写到这个地方
}
class ProvincesAdapter extends BaseAdapter {
@Override
public int getCount() {
if (mProviencesData == null || mProviencesData.size() == 0) {
return 0;
} else {
return mProviencesData.size();
}
}
@Override
public Object getItem(int position) {
return mProviencesData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mProviencesData == null || mProviencesData.size() == 0) {
return null;
}
String cityName = mProviencesData.get(position);
convertView = mInflater.inflate(R.layout.change_city_item_view,
parent, false);
ViewHolder holder = new ViewHolder();
holder.tvCityName = (TextView) convertView
.findViewById(R.id.tv_name);
holder.tvCityName.setText(cityName);
return convertView;
}
}
class ViewHolder {
private TextView tvCityName;
}
}
这是最后要选择的城市列表
public class CityActivity extends Activity implements OnClickListener,
OnItemClickListener {
// private final static String ACTION_CHOOSE_CITY = "com.demo.CityActivity.city";
private final static String EXTRA_PROVINCE = "Province";
private LayoutInflater mInflater = null;
private TextView titleView;
private Button backButton;
private Button optionButton;
private ListView lvProvinces;
private ArrayList<String> mCitiesData = null;
private CitiesAdapter adapter = null;
private String file2 = "province_city.xml";
private String parentArea = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.provinces_view);
initlayout();
}
public static void actionLaunch(Context context,String parent) {//跳到选择城市的ListView
Intent i = new Intent(context, CityActivity.class);
i.setAction(FirstActivity.ACTION_CHOOSE_CITY);
i.putExtra(EXTRA_PROVINCE, parent);
((Activity) context).startActivityForResult(i, FirstActivity.REQUEST_EVENT_CITY);
}
// public static void actionFilterDataLaunch(Context context){
// Intent i=new Intent(context,CityActivity.class);
// ((Activity) context).startActivityForResult(i, FirstActivity.REQUEST_EVENT_CITY);
//// context.startActivity(i);
// }
public void initlayout() {
mInflater = (LayoutInflater) this
.getSystemService(LAYOUT_INFLATER_SERVICE);
titleView = (TextView) findViewById(R.id.common_title_text);
backButton = (Button) findViewById(R.id.common_title_back);
optionButton = (Button) findViewById(R.id.common_title_option);
optionButton.setVisibility(View.INVISIBLE);
backButton.setOnClickListener(this);
// backButton.setText();
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
if (action != null) {
if (action.equals(FirstActivity.ACTION_CHOOSE_CITY)) {
parentArea =extras.getString(EXTRA_PROVINCE);
}
} else{
Log.i("TAG", "");
}
titleView.setText(parentArea);
addDataToUI();
lvProvinces = (ListView) this.findViewById(R.id.lv_provinces);
adapter = new CitiesAdapter();
lvProvinces.setAdapter(adapter);
lvProvinces.setOnItemClickListener(this);
}
private void addDataToUI() {
mCitiesData=Util.parseCityXML(Util.getFromAsset(file2, this), parentArea);//这里同ProvincesActivity中一样,解析xml再赋给ListView的数组
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.common_title_back) {
finish();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent data = new Intent();
String city=mCitiesData.get(position);
Bundle bundle = new Bundle();
bundle.putString(FirstActivity.EXTRA_CHOOSE_CITY, city);
data.putExtras(bundle);
this.setResult(RESULT_OK,
data);
finish();
}
class CitiesAdapter extends BaseAdapter {
@Override
public int getCount() {
if (mCitiesData == null || mCitiesData.size() == 0) {
return 0;
} else {
return mCitiesData.size();
}
}
@Override
public Object getItem(int position) {
return mCitiesData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mCitiesData == null || mCitiesData.size() == 0) {
return null;
}
String cityName = mCitiesData.get(position);
convertView = mInflater.inflate(R.layout.change_city_item_view,
parent, false);
ViewHolder holder = new ViewHolder();
holder.tvCityName = (TextView) convertView
.findViewById(R.id.tv_name);
holder.tvCityName.setText(cityName);
holder.tvArrow=(TextView)convertView.findViewById(R.id.tvArrow);
holder.tvArrow.setVisibility(View.GONE);
return convertView;
}
}
class ViewHolder {
private TextView tvCityName;
private TextView tvArrow;
}
}
最后是读取assets文件夹下xml,以及通过XmlPullParser解析给ListView
public class Util {
public static final String ENCODING = "UTF-8";
public static String getFromAsset(String fileName, Context context) {//读取文件的方法
String result = "";
try {
InputStream in = context.getResources().getAssets().open(fileName); // 从Assets中的文件获取输入流
int length = in.available(); // 获取文件的字节数
byte[] buffer = new byte[length]; // 创建byte数组
in.read(buffer); // 将文件中的数据读取到byte数组中
result = EncodingUtils.getString(buffer, ENCODING); // 将byte数组转换成指定格式的字符串
} catch (Exception e) {
e.printStackTrace(); // 捕获异常并打印
}
return result;
}
public static ArrayList<String> parseXML(String strXml) {//解析第一个xml文件
ArrayList<String> arraylist = new ArrayList<String>();
if (strXml == null || strXml.equals(""))
return null;
try {
XmlPullParser xmlParser = Xml.newPullParser();
xmlParser.setInput(new StringReader(strXml));
int evtType = xmlParser.getEventType();
while (evtType != XmlPullParser.END_DOCUMENT) {
switch (evtType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
String tag = xmlParser.getName();
/*
* if (tag.equalsIgnoreCase("Panel")) { Log.i("TAG",
* ">>>>>>>>>>>>>>已读到 " + tag +
* "<<<<<<<<<<<<<<<<<<<<<<<<<"); }
*/
if (tag.equalsIgnoreCase("province")) {
String province = xmlParser.nextText();
arraylist.add(province);
Log.i(tag, ">>>>>>>>>>>>>> province = " + province);
}
break;
case XmlPullParser.END_TAG:
break;
}
evtType = xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return arraylist;
}
public static ArrayList<String> parseCityXML(String strXml, String Province) {//解析第二个xml文件
ArrayList<String> citylist = new ArrayList<String>();
String province = null;
if (strXml == null || strXml.equals(""))
return null;
try {
XmlPullParser xmlParser = Xml.newPullParser();
xmlParser.setInput(new StringReader(strXml));
int evtType = xmlParser.getEventType();
while (evtType != XmlPullParser.END_DOCUMENT) {
switch (evtType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
String tag = xmlParser.getName();
if (tag.equalsIgnoreCase("Panel")) {
Log.i("TAG", ">>>>>>>>>>>>>>开始读取文档 " + tag
+ "<<<<<<<<<<<<<<<<<<<<<<<<<");
}
if (tag.equalsIgnoreCase("province")) {
province = xmlParser.nextText();
}
if (Province.equalsIgnoreCase(province)) {
if (tag.equalsIgnoreCase("city")) {
String district = xmlParser.nextText();
citylist.add(district);
Log.i("TAG", "citylist:" + citylist);
}
}
break;
case XmlPullParser.END_TAG:
break;
}
evtType = xmlParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
return citylist;
}
}