简体   繁体   English

使用Intent.putExtra发送数组

[英]Sending arrays with Intent.putExtra

I have an array of integers in the activity A: 我在活动A中有一个整数数组:

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

And I want to send that variable to the activity B, so I create a new intent and use the putExtra method: 我想将该变量发送到活动B,因此我创建了一个新的intent并使用了putExtra方法:

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

In the activity BI get the info: 在活动BI中获取信息:

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

But this is not really sending the array, I just get the value '0' on the arrayB. 但这并不是真的发送数组,我只是在arrayB上得到值'0'。 I've been looking for some examples but I didn't found anything so. 我一直在寻找一些例子,但我没有发现任何事情。

You are setting the extra with an array. 您正在使用数组设置额外的。 You are then trying to get a single int. 然后你试图得到一个int。

Your code should be: 你的代码应该是:

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

This code sends array of integer values 此代码发送整数值数组

Initialize array List 初始化数组列表

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

Add values to array List 将值添加到数组列表

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

Send the array list values to target activity 将数组列表值发送到目标活动

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

here you get values on targetActivty 在这里你可以获得targetActivty的值

Intent intent=getIntent();
ArrayList<String> test = intent.getStringArrayListExtra("test");
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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM