【问题标题】:class implementing Parcelable实现 Parcelable 的类
【发布时间】:2012-04-30 08:01:25
【问题描述】:

我想将一个类的数组列表从一个活动传递到另一个活动。为了做同样的事情,该类正在实现 Parcelable。问题是类中很少有字段为空。如何检查和仅发送以下值不为空。我认为这可以通过 writeToParcel() 中的简单 if/else 轻松完成,但如何在将参数作为 Parcel 的类的构造函数中执行相同操作。如下所示

private Student(Parcel in) {
}

发送空值时存在一些问题..

编辑:添加代码

    @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(id);
            dest.writeString(name);
            dest.writeString(grade);
            dest.writeString(dateOfBirth);
            dest.writeString(place);
                //Like wise there are many other fields
                //We have to write only values which are not null
}

       private Student(Parcel in) {
            id=in.readString();
            name=in.readString();
            grade=in.readString();
            dateOfBirth=in.readString();
            place=in.readString();
            //like wise have to read all other fields
           //we have to make sure we read only values which are not null
}

【问题讨论】:

  • 你怎么不实现Serializable呢?
  • 您试图实现的目标没有任何意义。您已经分析了您的问题并封装了您的领域对象,在学生级别以面向对象的方式进行更多思考。域对象的内部值不需要从外部关心和做特殊的条件代码。
  • 粘贴你的代码...处理空值应该不是问题

标签: android serialization


【解决方案1】:

最简单的方法是创建一个 Globalclass.java 并声明静态数组列表,如 public static ArrayList<String> arrayList = new ArrayList<String>(); 当你想使用Globalclass.arrayList = value;并在项目中使用任何软件。

使用intent的另一种传递方式

Intent i =new Intent(this,2activity.class);
i.putStringArrayListExtra(name, arrayList);

【讨论】:

  • 好吧,我真的不想在我的项目中创建任何最终可能导致内存崩溃的静态 ArrayList。我的项目中的 ArrayList 可能有多达 300 个类对象。每个类有大约 20 个元素。所以它不是创建静态 ArrayList 的明智想法。
  • Intent i =new Intent(this,2activity.class);i.putStringArrayListExtra(name, value);
  • 由于全局静态变量而被否决。这没有用(Intents 是为了这样做),并且只会导致崩溃(你的 Activity 被另一个调用,而静态变量仍然是 null?)
猜你喜欢
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
相关资源
最近更新 更多