将String从一个Activity传递给另一个Activity,android

时间:2015-11-01 06:00:48

标签: java 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上进行了大量搜索并尝试了大多数可能的解决方案,但仍未获得。

2 个答案:

答案 0 :(得分:0)

在你的活动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 :(得分:0)

我能够使用以下代码完成这项工作。

<强>活性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);
相关问题