简体   繁体   English

将数组传递给活动(Android)

[英]Passing an array to activity (Android)

In the activity A, I have built an array q1 of Question and I passed to activity B: 在活动A中,我构建了一个问题的数组q1,我传递给活动B:

Intent i = new Intent(getApplicationContext(), B.class);
i.putExtra("questions", q1);
startActivity(i);
finish();

In the activity B: 在活动B中:

Object c= getIntent().getExtras().getSerializable("questions");

Now, how can I reconvert "c" in an array of Questions? 现在,我如何在一系列问题中重新转换“c”? I can not make a cast (Question[]) 我无法进行演员表(问题[])

这会有所帮助。

 Question[] questions = (Question)context.getIntent().getExtras().get(key)

Your objects need to implement the Parcelable interface. 您的对象需要实现Parcelable接口。

In your Question class must implement parcelable interface. 在您的Question类中必须实现parcelable接口。 See the following code, 请参阅以下代码,

Question[] questions = //assign value;
Parcelable[] output = new Parcelable[questions.length];
for (int i=questions.length-1; i>=0; --i) {
    output[i] = questions[i];
}

Intent i = new Intent(...);
i.putExtra("QuestionArray", output);

//retreiving it from intent //从意图中撤回

Question[] questions = (Question[])intent.getParcelableArrayExtra("QuestionArray");

In your first activity you can send the array inside a bundle and then in the next activity that was created with the intent you can extract the array list from the bundle. 在第一个活动中,您可以在一个包内发送数组,然后在下一个使用intent创建的活动中,您可以从包中提取数组列表。

        Bundle b=new Bundle();
        b.putStringArrayList("option", optionMod);
        Intent i = new Intent(getApplicationContext(), ad45.hw.hwapp.confirmation.class);
        i.putExtras(b);
        startActivity(i); 

Then when you want to read the content in your new activity, create a new array List to store the one that was sent with the intent and extract the array from the bundle: 然后,当您想要读取新活动中的内容时,创建一个新的数组列表以存储随意图一起发送的数组,并从包中提取数组:

    public void getInfo(){
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
       options = extras.getStringArrayList("option"); 
     }
    }

Your Question object must implement the Parcelable interface. 您的Question对象必须实现Parcelable接口。 You can put only primitive objects or objects that implement Parcelable. 您只能放置实现Parcelable的原始对象或对象。

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

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