使用Intent.putExtra发送数组

Kit*_*inz 68 java android bundle android-intent android-activity

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

int array[] = {1,2,3};
Run Code Online (Sandbox Code Playgroud)

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

Intent i = new Intent(A.this, B.class);
i.putExtra("numbers", array);
startActivity(i);
Run Code Online (Sandbox Code Playgroud)

在活动BI中获取信息:

Bundle extras = getIntent().getExtras();
int arrayB = extras.getInt("numbers");
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*k B 86

您正在使用数组设置额外的.然后你试图得到一个int.

你的代码应该是:

int[] arrayB = extras.getIntArray("numbers");
Run Code Online (Sandbox Code Playgroud)

  • 哎哟! 我专注于putExtra和getExtras语法,我没有意识到错误很明显:D谢谢! (4认同)

Kha*_*bib 10

此代码发送整数值数组

初始化数组列表

List<Integer> test = new ArrayList<Integer>();
Run Code Online (Sandbox Code Playgroud)

将值添加到数组列表

test.add(1);
test.add(2);
test.add(3);
Intent intent=new Intent(this, targetActivty.class);
Run Code Online (Sandbox Code Playgroud)

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

intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test);
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)

在这里你获得targetActivty的值

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
Run Code Online (Sandbox Code Playgroud)