【发布时间】:2012-02-29 14:57:03
【问题描述】:
我想要做的是通过 Intents 发送一个对象;我一直在考虑像这样实现 Serializable:
Intent viewRecipe = new Intent(t, RecipeView.class);
Bundle input = new Bundle();
input.putSerializable("myRecipe", recipes.ReturnRecipe(position).toString());
viewRecipe.putExtras(input);
startActivity(viewRecipe);
但是,我猜是因为我有一个复杂的类它不起作用。谁能帮助解释我如何能够将此对象转换为序列化字符串?如果您知道一种更简单/更简单的方法,那也会很有帮助;可能还值得注意的是,我计划将其与 SQL 数据库进一步集成,但我现在被困住了。
班级是:
public class Recipe implements Serializable {
int mRating;
String mName;
String mDescription;
ArrayList<Ingredient> ingredients;
ArrayList<Step> instructions;
...
}
我不确定我是否必须重写“readObject”和“writeObject”,甚至我将如何开始这样做。作为旁注,成分和步骤不是复杂的类:
public class Ingredient {
String mName;
int mValue;
String mMeasurement;
...
}
public class Step {
int mIndex;
String task;
Date time;
...
}
长话短说,我不知道自己在做什么,可以使用一些指导。我已经阅读了很多关于如何序列化简单类的文章,但它们并没有真正帮助。
编辑:包括我得到的错误,当我从第二个活动中检索对象时,执行 Serilizable 会得到这个错误。
Intent myIntent = getIntent();
Bundle extras = myIntent.getExtras(); //breaks on this line
currentRecipe = (Recipe) extras.get("myRecipe");
02-29 15:15:56.521: E/AndroidRuntime(534): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pocket.recipes/com.pocket.recipes.RecipeView}: java.lang.ClassCastException: java.lang.String cannot be cast to com.pocket.recipes.Recipe
上面是“FATAL EXCEPTION: main”之后显示的行
然后我有很多错误只是说“在 android.app....”
我也有这行:
02-29 15:15:56.521: E/AndroidRuntime(534): Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to com.pocket.recipes.Recipe
抱歉,我是 Java/Android 新手
【问题讨论】:
标签: java android serialization