Which way is better for pass a large list of data from one activity to another activity - android?

谁说胖子不能爱 提交于 2021-02-08 08:48:39

问题


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:


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



回答2:


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.




回答3:


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



回答4:


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



回答5:


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



回答6:


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

}



回答7:


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



来源:https://stackoverflow.com/questions/41976522/which-way-is-better-for-pass-a-large-list-of-data-from-one-activity-to-another-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!