Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在Android中,通过Intent传递子类的实例后,无法从超类方法获取值_Java_Android - Fatal编程技术网

Java 在Android中,通过Intent传递子类的实例后,无法从超类方法获取值

Java 在Android中,通过Intent传递子类的实例后,无法从超类方法获取值,java,android,Java,Android,假设有两个名为Parent和Child的模型类,其中Parent类是Child类的超类 Class Parent { private String id; public void setId(String id) { this.id = id; } public void getId() { return id; } } Class Child extends Parent implements Serializable { private String

假设有两个名为Parent和Child的模型类,其中Parent类是Child类的超类

Class Parent {
    private String id;

    public void setId(String id) { this.id = id; }
    public void getId() { return id; }   
}

Class Child extends Parent implements Serializable {
    private String name;

    public void setName (String name){ this.name = name; }
    public void getName (){ return name; }
}
假设我的应用程序Activity1和Activity2中有两个活动。 在活动1中:

Class Activity1 extends Activity {
   //Create a instance of Class B and set some values.
   Child item = new Child();
   item.setId("001");
   item.setName("Test");

   //Start the Activity2 and put the instance of Child into it.
   Intent intent = new Intent(this, Activity2.class);
   intent.putExtra("item",item);
   startActivity(intent);
}
活动2中:

Class Activity2 extends Activity {
     if (getIntent().getSerializableExtra("item") != null){
        currentItem = (Child) getIntent().getSerializableExtra("item");
        Log.d("Current Item Name:", ": " currentItem.getName());
        Log.d("Current Item Id:", ": " + currentItem.getId());
     }
}
Current Item Name:: 001
Current Item Id:: null
输出:

Class Activity2 extends Activity {
     if (getIntent().getSerializableExtra("item") != null){
        currentItem = (Child) getIntent().getSerializableExtra("item");
        Log.d("Current Item Name:", ": " currentItem.getName());
        Log.d("Current Item Id:", ": " + currentItem.getId());
     }
}
Current Item Name:: 001
Current Item Id:: null
有人能帮我找出为什么我在这里得到“空”吗

您还需要序列化父类


您还需要序列化父类。

使类
父类
实现
可序列化
也只序列化父类或父类和子类?我假设父类就足够了。然而,在Android生态系统中,你最好坚持实现更轻量级的
Parcelable
。让类
Parent
implement
Serializable
也只实现父类或父类和子类?我想父类就足够了。然而,在Android生态系统中,您最好坚持实现更轻量级的
Parcelable