我尝试在活动之间传递对象,就像在How to pass an object from one activity to another on Android
中一样和SerializableTask正在正确创建,但是当我想在下一个活动中读取它时,它为空。
Task task = listOfTask.get(position);
Log.i(TAG, "recyclerViewEditTask: edit clicked for title: " +
task.getTitle());
SerializabledTask sTask = new SerializabledTask(task.getTitle(),
task.getDetails(), task.getTimeToDo(), task.getTag(),
task.getId(), task.isDone());
if(sTask == null)
Log.e(TAG, "recyclerViewEditTask: sTask IS NULL");
else {
Log.i(TAG, "recyclerViewEditTask: sTaskInfo: " + sTask.toString());
Intent editIntent = new Intent(ListOfTasksActivity.this, EditTaskActivity.class);
editIntent.putExtra("task", sTask);
startActivity(editIntent);
然后进入另一项活动
尝试获取Serializable对象的活动:
Intent i = getIntent();
SerializabledTask sTask = (SerializabledTask) i.getSerializableExtra("task");
if(sTask == null)
Log.e(TAG, "onCreate: sTASK IS NULL" );
和“onCreate:sTASK IS NULL”正在调用
当我尝试传递单个String时,它正常工作
Serializables类:
public class SerializabledTask implements Serializable {
String title, details, timeToDo, tag;
int id;
boolean done;
Task task;
public SerializabledTask(String title, String details, String timeToDo, String tag, int id, boolean done) {
this.title = title;
this.details = details;
this.timeToDo = timeToDo;
this.tag = tag;
this.id = id;
this.done = done;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getTimeToDo() {
return timeToDo;
}
public void setTimeToDo(String timeToDo) {
this.timeToDo = timeToDo;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
public Task getTask() {
return task;
}
public void setTask(Task task) {
this.task = task;
}
@Override
public String toString() {
return "SerializabledTask{" +
"title='" + title + '\'' +
", details='" + details + '\'' +
", timeToDo='" + timeToDo + '\'' +
", tag='" + tag + '\'' +
", id=" + id +
", done=" + done +
", task=" + task +
'}';
}
答案 0 :(得分:0)
您的模型类SerializableTask必须实现Serializable才能使代码正常工作。
public class SerializableTask implements Serializable {
...
}
同时强烈建议使用Parcelable而不是Serializable,因为它的速度要快得多。 资料来源:http://www.developerphil.com/parcelable-vs-serializable/