草庐IT

Android ArrayList<MyObject> 作为 parcelable 传递

coder 2023-06-07 原文

现已修改代码以反射(reflect)可接受的解决方案。

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

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

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

对话框 fragment

/**
 * 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 类

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

位置类

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

最佳答案

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

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

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

只需使用 putParcelableArrayList方法。

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

return fragmentInstance;

然后使用...检索它

localities = savedInstanceState.getParcelableArrayList(KEY_LOCALITY_LIST);

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

关于Android ArrayList<MyObject> 作为 parcelable 传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10953121/

有关Android ArrayList<MyObject> 作为 parcelable 传递的更多相关文章

  1. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  2. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  3. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

  4. ruby-on-rails - Nokogiri:使用 XPath 搜索 <div> - 2

    我使用Nokogiri(Rubygem)css搜索寻找某些在我的html里面。看起来Nokogiri的css搜索不喜欢正则表达式。我想切换到Nokogiri的xpath搜索,因为这似乎支持搜索字符串中的正则表达式。如何在xpath搜索中实现下面提到的(伪)css搜索?require'rubygems'require'nokogiri'value=Nokogiri::HTML.parse(ABBlaCD3"HTML_END#my_blockisgivenmy_bl="1"#my_eqcorrespondstothisregexmy_eq="\/[0-9]+\/"#FIXMEThefoll

  5. ruby - rails 3 redirect_to 将参数传递给命名路由 - 2

    我没有找到太多关于如何执行此操作的信息,尽管有很多关于如何使用像这样的redirect_to将参数传递给重定向的建议:action=>'something',:controller=>'something'在我的应用程序中,我在路由文件中有以下内容match'profile'=>'User#show'我的表演Action是这样的defshow@user=User.find(params[:user])@title=@user.first_nameend重定向发生在同一个用户Controller中,就像这样defregister@title="Registration"@user=Use

  6. ruby - 字符串文字中的转义状态作为 `String#tr` 的参数 - 2

    对于作为String#tr参数的单引号字符串文字中反斜杠的转义状态,我觉得有些神秘。你能解释一下下面三个例子之间的对比吗?我特别不明白第二个。为了避免复杂化,我在这里使用了'd',在双引号中转义时不会改变含义("\d"="d")。'\\'.tr('\\','x')#=>"x"'\\'.tr('\\d','x')#=>"\\"'\\'.tr('\\\d','x')#=>"x" 最佳答案 在tr中转义tr的第一个参数非常类似于正则表达式中的括号字符分组。您可以在表达式的开头使用^来否定匹配(替换任何不匹配的内容)并使用例如a-f来匹配一

  7. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  8. ruby - 在 Ruby 中按名称传递函数 - 2

    如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只

  9. ruby-on-rails - 应用程序的名称是否可以作为变量使用? - 2

    当我创建一个Rails应用程序时,控制台:railsnewfoo我的代码可以使用字符串“foo”吗?puts"Yourapp'snameis"+app_name_bar 最佳答案 Rails.application.class将为您提供应用程序的全名(例如YourAppName::Application)。从那里您可以使用Rails.application.class.parent获取模块名称。 关于ruby-on-rails-应用程序的名称是否可以作为变量使用?,我们在StackOve

  10. ruby-on-rails - 使用作为方法的值在 ruby​​ 中搜索哈希 - 2

    我在搜索我的值是方法的散列时遇到问题。我只是不想运行plan_type与键匹配的方法。defmethod(plan_type,plan,user){foo:plan_is_foo(plan,user),bar:plan_is_bar(plan,user),waa:plan_is_waa(plan,user),har:plan_is_har(user)}[plan_type]end目前如果我传入“bar”作为plan_type,所有方法都会运行,我怎么能只运行plan_is_bar方法呢? 最佳答案 这个变体怎么样?defmethod

随机推荐