我正在尝试将一些字符串数据从子活动发送到主要活动,并在编辑文本字段中显示该数据。 这是我在子活动中的代码:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent in = new Intent();
in.setClass(getApplicationContext(),
DelaySmsActivity.class);
in.putExtra("values", stringDataForSend);
setResult(RESULT_OK, in);
finish();
}
});
这里是主要活动的代码,我试图获得该值:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
parametar = data.getStringExtra("values");
editTextField.setText(parametar);
}
运行后,我的editTextField为空。
答案 0 :(得分:3)
为了传递简单的数据,比如字符串,我改用Bundles。
在你的onClick:
Intent yourIntent = new Intent(currentActivity.this, NextActivity.class);
Bundle yourBundle = new Bundle();
yourBundle.putString("name", string);
yourIntent.putExtra(yourBundle);
startActivity(yourIntent);
然后,在您的下一个活动的onCreate中,检索您的字符串,如:
Bundle bundle = getIntent().getExtras();
String passedValue = bundle.getString("name");
答案 1 :(得分:1)
试试这个让我们说你现在的活动是X而下一个活动是Y: -
Intent main= new Intent(X.this, Y.class);
main.putExtra("key", "somevalue");
X.this.startActivity(main);
在Y Activity onCreate
Intent intent = getIntent();
String value= intent.getStringExtra("key");
答案 2 :(得分:0)
因为您不在此处提交代码,这是一个可以帮助您的示例
当您致电活动时,请使用startActivityForResult() not startActivity()
public class CheckStartActivityForResult extends Activity {
int requestCode;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d("CheckStartActivity","OnCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i = new Intent(this,CalledActivity.class);
startActivityForResult(i, requestCode);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("CheckStartActivity","onActivityResult and resultCode = "+resultCode);
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==1){
Toast.makeText(this, "Pass", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Fail", Toast.LENGTH_LONG).show();
}
}
}
和被叫活动
public class CalledActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("CalledActivity","OnCreate ");
//String value = "rahul";
Intent in = new Intent();
setResult(1,in);//Here I am Setting the Requestcode 1, you can put according to your requirement
finish();
}
}