Android ArrayList<MyObject> 作为parcelable传递

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10953121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:33:02  来源:igfitidea点击:

Android ArrayList<MyObject> pass as parcelable

androidparametersparcelable

提问by MartinS

Code now modified to reflect the accepted solution.

现在修改了代码以反映已接受的解决方案。

This now serves as a working example of how to pass a custom ArrayList into a DialogFragment.

这现在用作如何将自定义 ArrayList 传递到 DialogFragment 的工作示例。

I am passing an ArrayList of custom objects to a DialogFragment using a Bundle on newInstance. The arraylist is received correctly in newInstance. The call to putParcelable executes fine (no errors), but putting breakpoints in the parcelable code in the ArrayList object shows that the parcel methods are not been called when setting or getting the data.

我正在使用 newInstance 上的 Bundle 将自定义对象的 ArrayList 传递给 DialogFragment。在 newInstance 中正确接收数组列表。对 putParcelable 的调用执行得很好(没有错误),但是在 ArrayList 对象的 parcelable 代码中放置断点表明在设置或获取数据时没有调用 parcel 方法。

Am i correct creating a LocalityList class for the ArrayList and making that parcelable, or should Locality class itself be parcelable ?

我是否正确为 ArrayList 创建 LocalityList 类并使该类可打包,或者 Locality 类本身应该是可打包的?

DialogFragment

对话片段

/**
 * Create a new instance of ValidateUserEnteredLocationLocalitySelectorFragment, providing "localityList"
 * as an argument.
 */
public static ValidateUserEnteredLocationLocalitySelectorFragment newInstance(LocalityList localityList) {

    ValidateUserEnteredLocationLocalitySelectorFragment fragmentInstance = new ValidateUserEnteredLocationLocalitySelectorFragment();

    // Supply location input as an argument.
    Bundle bundle = new Bundle();
    bundle.putParcelable(KEY_LOCALITY_LIST, localityList);
    fragmentInstance.setArguments(bundle);

    return fragmentInstance;
}


/**
 * Retrieve the locality list from the bundle
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mLocalityList = getArguments().getParcelable(KEY_LOCALITY_LIST);
}


 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.validate_user_entered_location, container, false);

    mLocalityListView = (ListView) view.findViewById(R.id.dialogLocalityListView);
    mAdapter = new SearchLocationLocalitiesListAdapter(getActivity(), mLocalityList);
    mLocalityListView.setAdapter(mAdapter);

    return view;
}

LocalityList class

LocalityList 类

import java.util.ArrayList;

import android.os.Parcel;
import android.os.Parcelable;

public class LocalityList extends ArrayList<Locality> implements Parcelable {

    private static final long serialVersionUID = 663585476779879096L;

    public LocalityList() {
    }

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

    private void readFromParcel(Parcel in) {
        this.clear();

        // First we have to read the list size
        int size = in.readInt();

        for (int i = 0; i < size; i++) {
            Locality r = new Locality(in.readString(), in.readDouble(), in.readDouble());
            this.add(r);
        }
    }

    public int describeContents() {
        return 0;
    }

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

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

    public void writeToParcel(Parcel dest, int flags) {
        int size = this.size();

        // We have to write the list size, we need him recreating the list
        dest.writeInt(size);

        for (int i = 0; i < size; i++) {
            Locality r = this.get(i);

            dest.writeString(r.getDescription());
            dest.writeDouble(r.getLatitude());
            dest.writeDouble(r.getLongitude());
        }
    }
}

Locality class

地区等级

import android.os.Parcel;
import android.os.Parcelable;


public class Locality implements Parcelable {

    private String mDescription;
    private double mLatitude;
    private double mLongitude;


    public Locality(String description, double latitude, double longitude) {
        super();
        this.mDescription = description;
        this.mLatitude = latitude;
        this.mLongitude = longitude;
    }

    public Locality(){
        super();
    }


    public String getDescription() {
        return mDescription;
    }

    public void setDescription(String description) {
        this.mDescription = description;
    }


    public double getLatitude() {
        return mLatitude;
    }

    public void setLatitude(double latitude) {
        this.mLatitude = latitude;
    }


    public double getLongitude() {
        return mLongitude;
    }

    public void setLongitude(double longitude) {
        this.mLongitude = longitude;
    }


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

    private void readFromParcel(Parcel in) {
        this.mDescription = in.readString();
        this.mLatitude = in.readDouble();
        this.mLongitude = in.readDouble();
    }

    public int describeContents() {
        return 0;
    }

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

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


    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mDescription);
        dest.writeDouble(mLatitude);
        dest.writeDouble(mLongitude);
    }
}

采纳答案by Mohammed Azharuddin Shaikh

Yes, make Localityclass itself Parcelable, and don't forgot to initialize

是的,让Locality类本身Parcelable,不要忘记初始化

ArrayList<Locality> mList= new ArrayList<Locality>();

回答by Caleb

I know this question is rather old but since I originally came here looking for answers, I wanted to share my experience.

我知道这个问题很老,但因为我最初来这里是为了寻找答案,所以我想分享我的经验。

Yes, you need to implement Parcelable for your Localityclass but that is it.

是的,您需要为您的Locality班级实现 Parcelable ,仅此而已。

If your LocalityListis ONLY a wrapper for ArrayList, then you do not need it.

如果您LocalityList只是 ArrayList 的包装器,那么您不需要它。

Just use the putParcelableArrayListmethod.

只需使用putParcelableArrayList方法。

ArrayList<Locality> localities = new ArrayList<Locality>;
...
Bundle bundle = new Bundle();
bundle.putParcelableArrayList(KEY_LOCALITY_LIST, localities);
fragmentInstance.setArguments(bundle);

return fragmentInstance;

And retrieve it using...

并使用...检索它

localities = savedInstanceState.getParcelableArrayList(KEY_LOCALITY_LIST);

So, unless you need the custom ArrayList for some other reason, you can avoid doing any of that extra work and only implement Parcelable for your Locality class.

因此,除非出于某种其他原因需要自定义 ArrayList,否则您可以避免做任何额外的工作,只为您的 Locality 类实现 Parcelable。

回答by blindado

The trick i normally use is to parse the list to Json using Gson (from google). On the other side i just parte the string in Json back to a new list.

我通常使用的技巧是使用 Gson(来自 google)将列表解析为 Json。另一方面,我只是将 Json 中的字符串重新分配到新列表中。

Never noticed any lag.

从来没有注意到任何滞后。