3

I need to pass a large list of data from one activity to another activity,which way is better?

First way(for example):

ArrayList<myModel> myList = new ArrayList<myModel>();
intent.putExtra("mylist", myList);

Second way(for example) :

ActivityTwo act = new ActivityTwo();
act.getDataMethod(listValues);
Intent i = new Intent(this, ActivityTwo.class);
startActivity(i);

And in another activity(ActivityTwo) I get data from getDataMethod.

  • 1
    You can't instantiate your `Activity`. So first approach will be good for you. – Piyush Feb 01 '17 at 09:49
  • 1
    [This link's solution might help you](http://stackoverflow.com/a/8109885/6609839) – hasan Feb 01 '17 at 10:06
  • 1
    [you can use this singleton pattern](http://stackoverflow.com/a/40838427/4772192) – Sachin Feb 01 '17 at 11:39
  • there can be one more way as in this answer :: [passing the whole list as string to other activity](http://stackoverflow.com/questions/41714944/click-on-listview-send-own-value-into-another-activity/41843199#41843199) – Anil Prajapati Feb 02 '17 at 05:38

7 Answers7

7

If the data you want to send is really big (around 1MB). The best way to pass it is to store it in persistent storage in ActivityA and access it in ActivityB.

The approach with passing it via Parcerable/Serializable is risky as you may end up with TransactionTooLargeException when trying to pass around 1MB of data.

The approach with passing it via Singleton class is even worse as when you are in ActivityB and application is recreated (it was long in background/memory was low) you will loose data from singleton (process is recreated) and nobody will set it, ActivityB will be launched and it wont have data from AcitvityA (as it was never created).

In general you shouldn't pass data through intents, you should pass arguments/identifiers which then you can use to fetch data from db/network/etc.

RadekJ
  • 2,835
  • 1
  • 19
  • 25
  • +1 for the fact that sending Lists of larger size do cause this exception, i have experienced it, what i did was to save the list in TinyDB at activity A and then retrieved it in Activity B, this is the only approach that is safe for lists that are really big – Hamza Khan Apr 30 '20 at 07:48
0

To me serialized objects/list is better way.

`Intent intent = .... 
Bundle bundle = new Bundle();
ArrayList<String> myList = new ArrayList<String>();
bundle.putSerializable("mylist", myList);
intent.putExtras(bundle);`
Usman Ghauri
  • 931
  • 1
  • 7
  • 26
  • Why? It is slower than parcelation and if transaction is larger than 1MB you will end up with TransactionTooLargeException and no clue where is it coming from. – RadekJ Sep 29 '19 at 06:56
0

Use the first approach. However you will need to use the following method call to put it into the Intent:

ArrayList<String> myList = new ArrayList<String>();
intent.putStringArrayListExtra("mylist",myList);

The to get the list out of the intent in the receiving Activity:

ArrayList<String> myList = getIntent().getStringArrayListExtra("mylist");
StuStirling
  • 15,601
  • 23
  • 93
  • 150
0

If you have a huge list of data it is better way to save the data in Singleton java class and use set/get to save & get the data in application level.

Sharing large data as intent bundle may chances to lose data.

Application.class

add this in you manifest file 
 <application
        android:name=".App"
        -----
</application>

public class App extends Application {

    public ArrayList<Object> newsList;
    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void setHugeData(ArrayList<Object> list){
        this.newsList = list;
    }

    public ArrayList<Object> getHugeData(){
       return newsList;
    }
}

in ActivityA.class
ArrayList<Object> info = new ArrayList<>();
// save data
((App)getApplication()).setHugeData(info);

in ActvityB.class
ArrayList<Object> info = new ArrayList<>();
// get the data
info = ((App)getApplication()).getHugeData();
mahesh87
  • 49
  • 4
  • Please get me a link for sample.Thanks –  Feb 01 '17 at 09:58
  • 1
    This solution is better http://stackoverflow.com/a/28174064/4813855 or your solution ? Thanks –  Feb 01 '17 at 10:20
  • using Parcelable is hard to maintain and time taking procedure. use a Singleton class or DataManager class is easy way to share the large data between Activities. – mahesh87 Feb 01 '17 at 10:24
  • It is very bad approach as you may navigate to ActivityB and then App may be recreated, in this scenario your singleton wont be set (ActivityA was never created and data was not set) and you will end up with NullPointerException in ActivityB – RadekJ Sep 29 '19 at 06:49
0

You can use such libraries as Eventbus to pass models through activities or you can put your model in ContentValues (https://developer.android.com/reference/android/content/ContentValues.html) class - it is parcable and you can pass it through intent. A good practice is to implement two methods in your Model class - toContentValues() and fromContentValues().

Something like this:

  public class DealShort extends BaseResponse implements ContentValuesProvider {

    @SerializedName("id")
    @Expose
    private long id = -1;

    @SerializedName("full_price")
    @Expose
    private double fullPrice;

 public static DealShort fromContentValues(ContentValues cv) {
        DealShort deal = new DealShort();
        deal.id = cv.getAsLong(DbContract.Product.SERVER_ID);
        deal.fullPrice = cv.getAsLong(DbContract.CategoriesProducts.CATEGORY_ID);
  }

  public ContentValues toContentValues() {        
        ContentValues cv = new ContentValues();
        cv.put(DbContract.Product.SERVER_ID, id);
        cv.put(DbContract.Product.FULL_PRICE, fullPrice);
        return cv;
  }

}
WorieN
  • 1,276
  • 1
  • 11
  • 30
0

Best way to pass large data list from one Activity to another in Android is Parcelable . You first create Parcelable pojo class and then create Array-List and pass into bundle like key and value pair and then pass bundle into intent extras.

Below I put one sample User Pojo class that implements Parcelable interface.

import android.os.Parcel;
import android.os.Parcelable;
/**
 * Created by CHETAN JOSHI on 2/1/2017.
 */

public class User implements Parcelable {

    private String city;
    private String name;
    private int age;


    public User(String city, String name, int age) {
        super();
        this.city = city;
        this.name = name;
        this.age = age;
    }

    public User(){
        super();
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @SuppressWarnings("unused")
    public User(Parcel in) {
        this();
        readFromParcel(in);
    }

    private void readFromParcel(Parcel in) {
        this.city = in.readString();
        this.name = in.readString();
        this.age = in.readInt();
    }

    public int describeContents() {
        return 0;
    }

    public final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        public User[] newArray(int size) {
            return new User[size];
        }
    };


    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(city);
        dest.writeString(name);
        dest.writeInt(age);
    }
}
ArrayList<User> info = new ArrayList<User>();
info .add(new User("kolkata","Jhon",25));
info .add(new User("newyork","smith",26));
info .add(new User("london","kavin",25));
info .add(new User("toranto","meriyan",30));

Intent intent = new Intent(MyActivity.this,NextActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("user_list",info );
intent.putExtras(bundle);`
startActivity(intent );
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43
-1

1,You can use Singleton class,like below code:

public class MusicListHolder {
    private ArrayList<MusicInfo> musicInfoList;

    public ArrayList<MusicInfo> getMusicInfoList() {
        return musicInfoList;
    }

    public void setMusicInfoList(ArrayList<MusicInfo> musicInfoList) {
        this.musicInfoList = musicInfoList;
    }

    private static final MusicListHolder holder = new MusicListHolder();

    public static MusicListHolder getInstance() {
        return holder;
    }
}

it's easy and useful!

2,You can use Application,just put your data in Application before you use it!

3,You can use Eventbus

4,You can put your data in a file/sqlite/...,maybe it's slow and conflict,but it's workable

Rickon Gao
  • 116
  • 6