使用枚举返回值后的java NullPointerException
我的转换器类:
public class CategoriesConverter extends Item_get {
@TypeConverter
public static Item_get.Food_type toFood_type(int food_type){
if(food_type == SWEETS.getCode()){
return SWEETS;
}else if(food_type == DRINKS.getCode()){
return DRINKS;
}else if(food_type == OTHER.getCode()){
return OTHER;
}else {
throw new IllegalArgumentException("Error Status");
}
}
@TypeConverter
public static int toInt(Item_get.Food_type food_type){
return food_type.getCode();
}
}
在我的Recyclerview
中,当我单击编辑图像时,我会将其放入下一个活动数据,如下所示:
@Override
public void onEditClick(Item_get item_get) {
Intent intent = new Intent(getActivity(), Edit_Delete_details.class);
intent.putExtra("KEY1", item_get);
intent.putExtra(Edit_Delete_details.EXTRA_ID, item_get.getId());
start_next_activity.launch(intent);
}
在第二个活动中,我是这样做的:
intent = getIntent();
item_get = intent.getParcelableExtra("KEY1");
id = intent.getIntExtra(EXTRA_ID, default: -1);
name = item_get.getName_Product();
amount = item_get.getAmount();
Item_get.Food_type food_type = item_get.food_type.getCode();
上面带有food_type
的行总是返回null
,我不知道为什么,因为在第一个活动中,类似这样的东西效果很好:
String f = String.valueOf(item_get.food_type); <-- Return String representation of enum like: SWEETS
OR
int n = item_get.food_type.getCode(); <-- Return integer of actually selected enum category like: 1
当我这样做时:
int n = item_get.food_type.getCode();
intent.putExtra("LINK", n);
效果很好。我在活动2中有它
但是为什么我不能把它和整个物品一起发送呢?就像它的名称产品和金额,而不是这个,我必须把它放在第二个变量
问题是,当我想将数据从活动2发送回活动1时,我遇到了如下错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.example.project.Item_get$Food_type.getCode()' on a null object reference
当我在CategoriesConverter类中更改时:
@TypeConverter
public static int toInt(Item_get.Food_type food_type){
From
return food_type.getCode();
to
return 1;
}
错误不会发生(这不是一个解决方案),但可能是一个提示
我的物品。类的枚举如下所示:
public enum Food_type{
SWEETS(1),
DRINKS(2),
OTHER(3);
private int code;
Food_type(int code){
this.code = code;
}
public int getCode(){
return code;
}
}
我还在数据库中添加了@TypeConverters
我读过enum是parcelabe对象
我正在使用RoomDatabase
那么,为什么我在从活动1更改为活动2后得到空对象呢
# 1 楼答案
我不认为枚举可以打包,但可以序列化。不过,通过实现该接口,可以将它们打包
我个人会添加代码作为额外的意图,并在另一面重新阅读。这是一个小的有效载荷,你不必实现可包裹