使用Intent.putExtra发送数组

时间:2010-10-03 01:12:14

标签: java android android-intent android-activity bundle

我在活动A中有一个整数数组:

int array[] = {1,2,3};

我想将该变量发送到活动B,因此我创建了一个新的intent并使用了putExtra方法:

Intent i = new Intent(A.this, B.class);
i.putExtra("numbers", array);
startActivity(i);

在活动B中,我获得了信息:

Bundle extras = getIntent().getExtras();
int arrayB = extras.getInt("numbers");

但这并不是真的发送数组,我只是在arrayB上得到值'0'。我一直在寻找一些例子,但我没有发现任何事情。

3 个答案:

答案 0 :(得分:84)

您正在使用数组设置额外内容。然后你试图获得一个int。

您的代码应为:

int[] arrayB = extras.getIntArray("numbers");

答案 1 :(得分:10)

此代码发送整数值数组

初始化数组列表

List<Integer> test = new ArrayList<Integer>();

将值添加到数组列表

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);

将数组列表值发送到目标活动

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);

在这里你可以获得targetActivty的值

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");

答案 2 :(得分:-2)

final static String EXTRA_MESSAGE = "edit.list.message";

Context context;
public void onClick (View view)
{   
    Intent intent = new Intent(this,display.class);
    RelativeLayout relativeLayout = (RelativeLayout) view.getParent();

    TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
    String message = textView.getText().toString();

    intent.putExtra(EXTRA_MESSAGE,message);
    startActivity(intent);
}