有人能告诉我到底如何使用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”);

这是非常容易实现意图在Android..它需要你从一个活动移动到另一个活动,我们有两个方法putExtra();现在我向你展示这个例子..

    Intent intent = new Intent(activity_registration.this, activity_Login.class);
                intent.putExtra("AnyKeyName", Email.getText().toString());  // pass your values and retrieve them in the other Activity using AnyKeyName
                        startActivity(intent);

现在我们必须从AnyKeyName参数中获取值,下面提到的代码将帮助完成这一点

       String data = getIntent().getExtras().getString("AnyKeyName");
        textview.setText(data);

我们可以很容易地从Intent中设置接收值,无论我们需要什么。

这是我一直在使用的,希望它能帮助到别人。简单而有感情。

发送数据

    intent = new Intent(getActivity(), CheckinActivity.class);
    intent.putExtra("mealID", meal.Meald);
    startActivity(intent);

获取数据

    int mealId;

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();

    if(bundle != null){
        mealId = bundle.getInt("mealID");
    }

干杯!

一个小补充:你不需要为键创建自己的名字,android提供了这些,f.ex。Intent.EXTRA_TEXT。修改接受的答案:

Intent i = new Intent(FirstScreen.)这一点,SecondScreen.class); 字符串strName = null; i.putExtra(意图。EXTRA_TEXT strName); 然后,要检索值,请尝试如下操作: 字符串部份; Bundle extras = getIntent().getExtras(); If (extras == null) { 部份=零; }其他{ 部份= extras.getString (Intent.EXTRA_TEXT); }

Intent intent = new Intent(view.getContext(), ApplicationActivity.class);
                        intent.putExtra("int", intValue);
                        intent.putExtra("Serializable", object);
                        intent.putExtra("String", stringValue);
                        intent.putExtra("parcelable", parObject);
                        startActivity(intent);

ApplicationActivity

Intent intent = getIntent();
Bundle bundle = intent.getExtras();

if(bundle != null){
   int mealId = bundle.getInt("int");
   Object object = bundle.getSerializable("Serializable");
   String string = bundle.getString("String");
   T string = <T>bundle.getString("parcelable");
}