有人能告诉我到底如何使用getExtra()和putExtra()的意图吗?实际上我有一个字符串变量str,它存储一些字符串数据。现在,我想把数据从一个活动发送到另一个活动。

  Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
  String keyIdentifer  = null;
  i.putExtra(strName, keyIdentifer );

然后在SecondScreen.java中

 public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table);
        TextView userName = (TextView)findViewById(R.id.userName);
        Bundle bundle = getIntent().getExtras();

        if(bundle.getString("strName")!= null)
        {
            //TODO here get the string stored in the string variable and do 
            // setText() on userName 
        }

    }

我知道这是一个非常基本的问题,但不幸的是,我被困在这里了。 请帮助。

谢谢,

编辑:这里的字符串,我试图从一个屏幕传递到另一个是动态的。 也就是我有一个editText,在那里我获取字符串,不管用户类型是什么。然后在myEditText.getText(). tostring()的帮助下。我得到输入的值作为一个字符串,然后我必须传递这个数据。


当前回答

对于这个任务,一个内联代码就足够了。这对我来说毫不费力。 面向android开发者。 .getExtras字符串strValue = Objects.requireNonNull (getIntent () ()) .getString(“string_Key”);

其他回答

你可以简单地使用静态变量来存储你的编辑文本的字符串,然后在其他类中使用该变量。希望这能解决你的问题

在意图对象中放入字符串

  Intent intent = new Intent(FirstActivity.this,NextAcitivity.class);
  intent.putExtra("key",your_String);
  StartActivity(intent);

onCreate方法中的NextAcitvity获取字符串

String my_string=getIntent().getStringExtra("key");

那是一种简单易行的方法

对于这个任务,一个内联代码就足够了。这对我来说毫不费力。 面向android开发者。 .getExtras字符串strValue = Objects.requireNonNull (getIntent () ()) .getString(“string_Key”);

最好的方法…

SendingActivity

Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);
intent.putExtra("keyName", value);  // pass your values and retrieve them in the other Activity using keyName
startActivity(intent);

RecievingActivity

 Bundle extras = intent.getExtras();
    if(extras != null)
    String data = extras.getString("keyName"); // retrieve the data using keyName 

///接收数据的最短方式

String data = getIntent().getExtras().getString("keyName","defaultKey");

//这需要api 12。 //第二个参数是可选的如果keyName为空,则使用defaultkey作为数据。

在Intent类中更新。

使用hasExtra()检查意图是否在key上有数据。 现在可以直接使用getStringExtra()。

传递数据

intent.putExtra(PutExtraConstants.USER_NAME, "user");

获取数据

String userName;
if (getIntent().hasExtra(PutExtraConstants.USER_NAME)) {
    userName = getIntent().getStringExtra(PutExtraConstants.USER_NAME);
}

作为最佳实践,始终将键放在常量中。

public interface PutExtraConstants {
    String USER_NAME = "USER_NAME";
}