2012-04-30 49 views
2

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

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 
} 
+0

你怎么不执行'Serializable'而不是通过? – Jave

+0

你试图达到什么没有任何意义。您已经分析了您的问题并封装了您的域对象,在学生层面以OO方式思考更多。没有必要关心和做外部的域对象的内部值的特殊条件代码。 – yorkw

+0

粘贴你的代码......它应该不是一个问题来处理空值 – waqaslam

回答

-1

Simpest的方法是创建一个Globalclass.java和声明静态的ArrayList像公共静态ArrayList<String> arrayList = new ArrayList<String>(); 当你想使用Globalclass.arrayList = value;并在项目中使用任何软件。

另一种方式使用意图

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

以及我真的不想创建任何静态ArrayList,最终可能导致内存崩溃在我的project.ArrayList中我的项目可能有多达300个类对象。每个类都有大约20个元素。所以创建静态ArrayList不是明智的想法。 – androidGuy

+0

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

+0

由于全局静态变量而被降级。这是没有用的('Intent'被做成这样做),并且只能导致崩溃(你从另一个调用'Activity'时,静态变量仍为'null'?) –

相关问题