![](/img/trans.png)
[英]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.