GiuseppeLabanca
GiuseppeLabanca

Reputation: 265

Passing an array to activity (Android)

In the activity A, I have built an array q1 of Question and I passed to activity B:

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

In the activity B:

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

Now, how can I reconvert "c" in an array of Questions? I can not make a cast (Question[])

Upvotes: 0

Views: 107

Answers (4)

GiuseppeLabanca
GiuseppeLabanca

Reputation: 265

Your Question object must implement the Parcelable interface. You can put only primitive objects or objects that implement Parcelable.

Upvotes: 0

user2618291
user2618291

Reputation:

this will be helpful.

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

Upvotes: 2

Lewis
Lewis

Reputation: 70

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.

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

Upvotes: 0

keerthana murugesan
keerthana murugesan

Reputation: 581

Your objects need to implement the Parcelable interface.

In your Question class must implement parcelable interface. 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");

Upvotes: 0

Related Questions