0

I am new to android programming, and I am trying to send an array of custom objects to a different activity. In the first activity I have a function that creates an intent and adds the array of objects to it:

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    nextScreen.putExtra("array", tasks);
    startActivity(nextScreen);
}

However, I'm not sure how to get that data at the next screen.

Is there any way to get that array in the code for the next activity even though "tasks" is an array of custom objects?

1

3 Answers 3

6

Did you try it with Gson?

public void openSchedule() {
    Intent nextScreen = new Intent(getApplicationContext(), Schedule.class);
    String arrayAsString = new Gson().toJson(tasks);
    nextScreen.putExtra("array", arrayAsString);
    startActivity(nextScreen);
}

In your second activity, parse the extra data back into the List<T>

public void parseBack(){
    String arrayAsString = getIntent().getExtras().getString("array");
    List<YourType> list = Arrays.asList(new Gson().fromJson(arrayAsString, YourType[].class));
}
Sign up to request clarification or add additional context in comments.

6 Comments

Perfect solution.
Lol, almost forgot abut this one. The sad thing is that I even use Gson in other part of my app to save my object array in shared preferences :/ +1 'cause you reminded me of this
This worked for me. But I need to store the object in an array list not a regular list. How do I need to edit this piece of code to do so?
@VaskoVasilev just remove the Arrays.asList and you'll get an array.
It still gives the incompatible types error. The value returned is: 'com.example.pogolemotoproektce.Classes.Book[]'
|
1

Have your custom object implement Parcelable, in order to make use of putParcelableArrayListExtra from the Intent class.

Comments

0

You didn't search a lot...

Check this for Parcelable interface : How to send an object from one Android Activity to another using Intents?

edit : This too, https://guides.codepath.com/android/Using-Parcelable

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.