【问题标题】:Pass an array of custom objects + Android传递自定义对象数组 + Android
【发布时间】:2011-03-28 14:10:48
【问题描述】:

我对 Android 开发非常陌生,在这里遇到了一个小问题。 我有一堂动物课。我需要在两个活动之间传递一组 Animal 类。我搜索了论坛,发现这可以用 Parceable 完成,但我无法完全理解。我尝试使用 Serializable 但遇到异常。 请指导我如何做到这一点?

【问题讨论】:

    标签: android


    【解决方案1】:

    推杆:

    ArrayList<Animal> animals = new ArrayList<Animal>();
    //fill your list with animals here
    
    intent.putExtra("animals", animals);
    

    检索:

    ArrayList<Animal> animals = (ArrayList<Animal>) getIntent()
                            .getSerializableExtra("animals");
    

    你的类 Animal 应该实现 Serializable。

    编辑: 请注意,这种方法易于实现但效率低下。序列化和反序列化对象需要时间,并且如果数组很大(例如,100 多个对象或 10 多个复杂的重对象),可能会导致活动转换的明显延迟。因此,请将此方法视为临时方法,不要在生产代码中使用它。

    为了提高效率,您可以按照 David Caunt 的建议使用 Parcelable。这是一个易于使用的代码生成器,可避免开发人员编写样板代码:Parcelabler。

    一个不错的选择是在每个需要它的Activity 中从本地数据库中获取和检索数据时将数据存储在本地 SQLite 数据库中。因此,您将只通过意图传递内容网址。

    【讨论】:

      【解决方案2】:

      你应该implement Parcelable 然后你可以传递你的对象。您基本上添加了几个方法来将您的对象转换为 Parcel,反之亦然。

      Parcelling 与 Serialization 类似,但又不一样。把它想象成重建对象。

      有一个例子完全符合您的要求here。

      【讨论】:

        【解决方案3】:

        你的 Animal 类应该实现 Serializable。

        输入数据

           ArrayList<Animal> animals = new ArrayList<Animal>();
        
                    Intent intent = new Intent(MainActivity.this,
                            AnimalListActivity.class);
        
                    Bundle bundleObject = new Bundle();
                    bundleObject.putSerializable("animal", animals);
        
                    intent.putExtras(bundleObject);
        
                    startActivity(intent);
        

        获取数据

         ArrayList<Animal> animals = new ArrayList<Animal>();
         @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.animal_activity);
        
            Bundle bundleObject = getIntent().getExtras();
            animals = (ArrayList<Animal>) bundleObject
                    .getSerializable("animal");
        
        
            }
         }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-15
          • 1970-01-01
          • 2015-11-07
          • 1970-01-01
          • 2018-08-10
          • 2013-03-22
          相关资源
          最近更新 更多