简体   繁体   中英

Pass String from one Activity to another activity, android

Here is my code below for passing string from one intent to another:

Activity1

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();
    }
});

Activity2

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.

Have also tried using

 Intent i = getIntent();
 i.getStringExtra("Caption");    // Still no result

Have searched a lot on StackOverflow and tried most of the possible solutions but still not getting.

In your activity 1 : In you onCreate()

     EditText et = (EditText) findViewById(R.id.captionText);

in your 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);
   }

In your activity 2 onCreate():

   String personStr = getIntent().getExtras().getString("PERSON_KEY");
   // do nullcheck after getting from bundle..

I was able to make this work using the below code.

Activity1

Intent i = new Intent(MainActivity.this,Activity2.class);
i.putExtra("Caption",s);
startActivity(i);
finish();

Activity2

Bundle b = getIntent().getExtras();
String str = b.getString("Caption");
Log.i("string",str);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM