如何使用 putExtra() 和 getExtra() 传递和获取字符串数据?

367

请问如何使用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()的帮助将输入的值作为字符串获取,然后我必须传递这些数据。


i.putExtra(strName, keyIdentifer); 这个语句中有一个strName变量,而bundle.getString("strName")中则有"strName"字符串。它是 intent.putExtra(key, value) 和intent.getExtras().getString(key);确保在put和get中使用相同的key。 - seema
18个回答

458

使用此方法进行文件的“放置”...

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

12
“savedInstanceState...”和“...getSerializable”代码是用于处理屏幕旋转时保存和恢复数据的。如果不是用于处理屏幕旋转,那么这些代码是用于什么目的? - AJW
1
我正在使用Android 3.0.1版本,并且我不得不使用this.getActivity().getIntent().getExtras() - Tyler
如果您使用PendingIntents,需要使用“PendingIntent.FLAG_UPDATE_CURRENT”标志:Intent intent = new Intent(context, MainActivity.class); intent.putExtra("button_id", 1); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_test_widget); views.setOnClickPendingIntent(R.id.my_test_widget_button_1, pendingIntent); - Matthias Luh

80

第一屏.java

text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);

button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();

        Intent ii=new Intent(MainActivity.this, newclass.class);
        ii.putExtra("name", s);
        startActivity(ii);
    }
});

第二屏幕.java

public class newclass extends Activity
{
    private TextView Textv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Intent iin= getIntent();
        Bundle b = iin.getExtras();

        if(b!=null)
        {
            String j =(String) b.get("name");
            Textv.setText(j);
        }
    }
}

56

最佳方法...

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

接收活动

 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为null,则使用defaultkey作为数据。


24

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

发送数据

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

干杯!


1
我仍然不时地需要提醒自己,如何正确地完成这个..哈哈! - Sindri Þór

10

在Android中实现意图(intent)非常容易。它可以让你从一个活动(activity)移动到另一个活动,我们有两种方法:putExtra();getExtra();。现在我向您展示一个例子。

    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中获取接收值,无论我们何时需要。


7
一个小补充:你不必为密钥创建自己的名称,安卓已经提供了这些,例如Intent.EXTRA_TEXT。修改接受的答案:
Intent i = new Intent(FirstScreen.this, SecondScreen.class);   
String strName = null;
i.putExtra(Intent.EXTRA_TEXT, strName);

Then, to retrieve the value try something like:

String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
    newString= null;
} else {
    newString= extras.getString(Intent.EXTRA_TEXT);
}

6

发送

startActivity(new Intent(First.this, Secend.class).putExtra("key",edit.getText.tostring));

获取

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

6
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);

应用程序活动

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

5

Intent类中的更新。

  • 使用hasExtra()检查意图是否具有关键数据。
  • 现在可以直接使用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";
}

为什么PutExtraConstants是一个接口? - Big_Chair
@Big_Chair 因为 PutExtraConstants 类只包含常量(publicstaticfinal)。因此最好使用接口来定义常量。 - Khemraj Sharma

4

将字符串放入Intent对象中

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

在 onCreate 方法中获取字符串的下一个活动
String my_string=getIntent().getStringExtra("key");

这是一种简单易懂的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接