如何对字符串数据使用putExtra()和getExtra()

如何对字符串数据使用putExtra()和getExtra()

有谁能告诉我如何准确地使用getExtra()putExtra()为了目的?实际上,我有一个字符串变量,比如说str,它存储一些字符串数据。现在,我想将这些数据从一个活动发送到另一个活动。

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

然后在SecdScreen.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 
        }

    }

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

谢谢,

编辑:在这里,我试图从一个屏幕传递到另一个屏幕的字符串是动态的。也就是说,我有一个edtext,在其中我可以得到任何用户类型的字符串。然后在.的帮助下myEditText.getText().toString()..我将输入的值作为字符串,然后必须传递这些数据。


长风秋雁
浏览 2560回答 3
3回答

慕莱坞森

用这个“放”文件.。Intent i = new Intent(FirstScreen.this, SecondScreen.class);   String strName = null;i.putExtra("STRING_I_NEED", strName);然后,要检索该值,请尝试如下所示:String newString;if (savedInstanceState == null) {     Bundle extras = getIntent().getExtras();     if(extras == null) {         newString= null;     } else {         newString= extras.getString("STRING_I_NEED");     }} else {     newString= (String) savedInstanceState.getSerializable("STRING_I_NEED");}

呼唤远方

最好的方法.。发送活动Intent intent = new Intent(SendingActivity.this, RecievingActivity.class);intent.putExtra("keyName", value);   // pass your values and retrieve them in the other Activity using keyNamestartActivity(intent);循环活性 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作为数据。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android