使用Intent.putExtra发送数组

69

我在Activity A中有一个整数数组:

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

我希望将该变量发送到活动B,因此我创建了一个新的意图并使用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'。我一直在寻找一些例子,但是没有找到什么有用的。


2
我需要的答案就在你的问题中。我需要知道如何使用.getExtras() - MikeyE
3个回答

91

你正在使用数组设置额外数据,然后尝试获取单个整数。

你的代码应该是:

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

6
哎呀!我太专注于putExtra和getExtras的语法了,以至于没有意识到错误是如此明显 :D 谢谢! - Kitinz
@Kitinz +1 非常友好的社区...我喜欢那个 :) - Adnan

9
这段代码发送整数值数组。
初始化数组列表。
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);

在这里,您可以获取目标活动的值。

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

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

1
我觉得你看了这段代码之后就会知道你犯了什么错误......:) - paladiya chirag

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