gpt4 book ai didi

java - Android:自定义 Parcelable 类在没有抛出异常的情况下使应用程序崩溃

转载 作者:太空狗 更新时间:2023-10-29 14:12:42 24 4
gpt4 key购买 nike

我有一个 Android 应用程序,其中包含实现 Parcelable 接口(interface)的自定义对象。我设置它的方式是我的程序最初创建一个 ArrayList自定义类的 Products来自 bundle 中的文件。我可以看到并确认数组列表及其实例变量已正确填充。这个类有几个实例变量,一个是另一个ArrayList但是有了 String类(class)。记住这个事实。

我正在尝试通过 ArrayList<Product>像这样进入一个新 Activity :

  try {
Intent i = new Intent(RootActivity.this, ProductsActivity.class); //Intent from this activity to the next
i.putParcelableArrayListExtra("Products", app_products); //Puts my ArrayList<Class A> as an extra
startActivity(i); //Launch the activity

}
catch(Exception e){
Log.d("Activity Error", "Error Here:" + e.getMessage());
}

我正在通过拉取 ArrayList 从我的新 Activity 中的 Intent 收集信息通过使用

     app_products = getIntent().getParcelableArrayListExtra("Products");

对于我的自定义类,它看起来像这样,以及已实现的 Parcelable 方法。

public class Product implements Parcelable{
private String name;
private String cost;
private ArrayList<String> similarItems;

public Product{
name = null;
cost = null;
similarItems = new ArrayList<String>();
}

public Product(String name, String cost){
this();
this.name = name;
this.cost = cost;
}

public addSimilarItem(String item){
similarItems.add(item);
}

public static final Parcelable.Creator<Product> CREATOR
= new Parcelable.Creator<Product>()
{
public Product createFromParcel(Parcel in) {
return new Product(in);
}

public Product[] newArray(int size) {
return new Product[size];
}
};

public int describeContents(){
return 0;
}

private Product(Parcel in){
name = in.readString();
cost = in.readString();
similarItems = in.readArrayList(String.class.getClassLoader());
}

public void writeToParcel(Parcel out, int flags){
out.writeString(name);
out.writeString(cost);
out.writeList(similarItems);
}
}

所以这很好用 WITHOUT 我的字符串数组列表被添加到类中

注释掉out.writeList(similarItems);还有similarItems = in.readArrayList(String.class.getClassLoader());

但是一旦您将它们重新添加到类中,应用程序就会崩溃,但它甚至不会抛出调试消息。我已经把所有东西都包裹起来了 try-catch语句和 android 甚至不报告应用程序崩溃与跳板上的正常对话框。我真的很茫然。

值得一提的是,尽管 android 不会抛出异常,但我已经使用了一些日志语句来了解程序崩溃的位置。我可以看到我的 ArrayList 中的所有项目都经过 writeToParcelMethod 并完成写入。永远不会调用 Product(Parcel in) 方法。最后,我还可以看到我正在启动新 Activity 的类(class)进入 Pause State。我的新 Activity 从未创建。

如果我可以提供任何其他信息,请告诉我。

最佳答案

可以肯定您的问题是 writeList() 的使用。 writeList() 似乎表明它遵循与列表中包含的项目的 writeValue() 相同的契约(Contract)。 readList() 然而,似乎表明值必须是 Parcelable(String 不是)。

无论哪种方式,通常这些调用都必须非常具体地链接到它们的反函数(例如,writeString() 必须用 readString() 读入,而不是 readValue()) 所以你应该使用提供的方法来读/写 String Lists:

// Takes in a List<String> which may be null
out.writeStringList(similarItems);

// Returns either null or a new ArrayList<String> with the contents
similarItems = in.createStringArrayList();

关于java - Android:自定义 Parcelable 类在没有抛出异常的情况下使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25652753/

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