[英]Pass a String from one Activity to another Activity on AndroidStudio
[英]Pass String from one Activity to another activity, android
这是我的以下代码,用于将字符串从一种意图传递到另一种意图:
活动1
Button saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText et = (EditText) findViewById(R.id.captionText);
String s = et.getText().toString();
System.out.println("***caa" + s);
//text is printed here which i type in editText of my app.
Intent i = new Intent(Activity1.this,Activity2.class)
i.putExtra("Caption",s);
startActivity(i);
finish();
}
});
活动2
Bundle b = getIntent.getExtras();
String str = b.getExtraString("Caption");
System.out.println("***A2 ",str); // here i m getting null
TextView tv = (TextView) findViewById(R.id.Text);
tv.setText(str);
// and therefore here text is not able to set in textView.
也尝试过使用
Intent i = getIntent();
i.getStringExtra("Caption"); // Still no result
在StackOverflow上进行了大量搜索,并尝试了大多数可能的解决方案,但仍然没有成功。
在您的活动1中:在您中onCreate()
EditText et = (EditText) findViewById(R.id.captionText);
在您的onClick()中
@Override
public void onClick(View v) {
String personStr = et.getText().toString();
if(personStr != null && !personStr.trim().equals("")) {
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("PERSON_KEY", personStr);
startActivity(intent);
}
在您的活动2 onCreate()中:
String personStr = getIntent().getExtras().getString("PERSON_KEY");
// do nullcheck after getting from bundle..
我可以使用下面的代码来完成这项工作。
活动1
Intent i = new Intent(MainActivity.this,Activity2.class);
i.putExtra("Caption",s);
startActivity(i);
finish();
活动2
Bundle b = getIntent().getExtras();
String str = b.getString("Caption");
Log.i("string",str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.