【问题标题】:Sending arrays with Intent.putExtra使用 Intent.putExtra 发送数组
【发布时间】:2011-04-20 08:59:23
【问题描述】:

我在活动 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");

但这并不是真正发送数组,我只是在数组B 上得到值“0”。我一直在寻找一些示例,但没有找到任何示例。

【问题讨论】:

  • 我需要的答案在你的问题中。这是我需要的如何使用.getExtras()

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


【解决方案1】:

您正在使用数组设置额外内容。然后,您尝试获取单个 int。

你的代码应该是:

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

【讨论】:

  • 哎哟!我专注于 putExtra 和 getExtras 语法,我没有意识到错误是如此明显:D 谢谢!
  • @Kitinz +1 对社区非常友好......我喜欢这个:)
【解决方案2】:

此代码发送整数值数组

初始化数组列表

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

【讨论】:

    【解决方案3】:
    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);
    }
    

    【讨论】:

    • 我想你在看到这段代码后就会知道你在哪里犯了错误......:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 2012-08-24
    • 1970-01-01
    相关资源
    最近更新 更多