gpt4 book ai didi

java - 在 Android 上序列化复杂对象 (Java)

转载 作者:行者123 更新时间:2023-11-29 08:08:45 26 4
gpt4 key购买 nike

我想做的是通过 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”,甚至不确定我将如何开始这样做。作为旁注,Ingredient 和 Step 不是复杂的类:

public class Ingredient {

String mName;
int mValue;
String mMeasurement;
...
}

public class Step {

int mIndex;
String task;
Date time;
...
}

长话短说,我不知道自己在做什么,需要一些指导。我已经阅读了一些关于如何序列化简单类的文章,但它们并没有真正帮助。

编辑:包括我得到的错误,当我从第二个 Activity 中检索对象时,只是实现 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 的新手

最佳答案

除非无法避免,否则在通过 Intents 发送数据时不应使用 Serializable(出于性能考虑)。你应该实现 Parcelable接口(interface)代替。有很多麻烦,但它实际上很简单,除非你有一个非常复杂的类。您还可以在子类上实现 Parcelable,然后只需使用 writeParcelableArray() 来获取成分和步骤列表。

关于java - 在 Android 上序列化复杂对象 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9501368/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com