标签:
起初是在启动后的Activity中的onPause()中调用setResult(int ,Intent)来设置返回的Intent,但是在返回后的Activity中的onActivityResult(int,int,Intent)得到的Intent是空值NULL。
这是启动代码
findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, MainActivity2.class); Bundle sendBundle = new Bundle(); sendBundle.putCharSequence("str", "From MainActivity.class"); intent.putExtra("sendBundle", sendBundle); startActivityForResult(intent,0x1001); } }); Log.i(TAG, "onCreated");
protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if(data!=null){ String str = data.getStringExtra("return"); Log.i(TAG,str+" "+requestCode+" "+resultCode); if(resultCode==0x1001){ TextView textView = (TextView)findViewById(R.id.textView1); textView.setText(str); } }else{ Log.i(TAG,"data is null"); } }
上面是结果返回的回调方法重写
下面是错误的setResult(int ,Intent)代码
protected void onPause(){ Intent intent = new Intent(); intent.putExtra("return", "Return me"); setResult(0x1001, intent); }
在找到原因后,将上面的代码修改到onCreate(Bundle)中,增加一个Button并添加onClick(View)
findViewById(R.id.button2).setOnClickListener(new OnClickListener(){ public void onClick(View v){ Intent intent = new Intent(); intent.putExtra("return", "Return me"); setResult(0x1001, intent); finish(); //这里很关键,只有这样,才能把Intent传回到启动它的Activity中,并关闭当前的Activity } });
关于Activity.startActivityForResult(Intent ,int )使用
标签:
原文地址:http://my.oschina.net/u/1582029/blog/495642