[英]NullPointerException after returning value using enum
我的轉換器 class:
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 中有它。
但是為什么我不能用整個 item_get object 發送它? 就像 Name Product 和 Amount 一樣,我必須把它放到第二個變量中?
問題是當我想將數據從活動 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 class 時:
@TypeConverter
public static int toInt(Item_get.Food_type food_type){
From
return food_type.getCode();
to
return 1;
}
不會發生錯誤(這不是解決方案),但可能是提示。
我的 Item_get.class 有這樣的枚舉:
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
。
我讀過枚舉是包裹對象。
我正在使用RoomDatabase
那么為什么我在從活動 1 更改為活動 2 后得到 null object 呢?
我認為枚舉不是可包裹的,而是可序列化的。 但是,您可以通過實現接口使它們可打包。
我個人會添加代碼作為額外的意圖,然后在另一邊讀回來。 這是一個很小的有效載荷,你不必實現 parcelable。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.