我开始将Kotlin与Java结合使用。
下面是java代码。不引发空指针异常
initFoodQuantitySpinner();
CartDb cartDb = new CartDb(getActivity());
try {
P.addToCart(getActivity(), food.getId(), food.getPrice(), foodQuantity);
} catch (Exception e) {
e.printStackTrace();
}
FoodCartModel foodCartModel = new FoodCartModel(new Food(food.getId(),
food.getName(), 0, "", "",
food.getPrice(), 0,
0, null, "", "", null));
cartDb.insertFood(foodCartModel);
if (getActivity() != null)
getActivity().invalidateOptionsMenu();
Kotlin中的以下代码引发空指针异常。
spinFoodQuantity.visibility = View.VISIBLE
val cartDb = CartDb(context)
val id = food.id
val name = food.name
val price = food.price
try {
P.addToCart(activity, id, price, foodQuantity)
} catch (e: Exception) {
e.printStackTrace()
}
val foodCartModel = FoodCartModel(
Food(id, name, 0, "", "", price, 0,
0, null!!, "", "", null!!),
foodQuantity)
cartDb.insertFood(foodCartModel)
activity!!.invalidateOptionsMenu()
在共享pref中添加到购物车功能
public static synchronized void addToCart(Context context, int id, int price, int quantity)
throws JSONException {
assurePrefNotNull(context);
String data = getCartData(context);
JSONArray array;
if (data.equals(""))
array = new JSONArray();
else array = new JSONArray(data);
JSONObject item = new JSONObject();
item.put("id", id);
item.put("price", price);
item.put("quantity", quantity);
array.put(item);
prefsEditor.putString(PREF_CART_DATA, array.toString());
prefsEditor.commit();
}
有人能解释一下kotlin抛出空指针异常的错误在哪里吗?android studio显示关于无法访问代码的警告(针对kotlin中的以下代码)
val foodCartModel = FoodCartModel(
Food(id, name, 0, "", "", price, 0,
0, null!!, "", "", null!!),
foodQuantity)
cartDb.insertFood(foodCartModel)
activity!!.invalidateOptionsMenu()