How can I bypass an empty JSON
value and give it a default value.
This is my code:
private static Cursor extractFeatureFromJson(String foodJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(foodJSON)) {
return null;
}
try {
JSONArray foodArray = new JSONArray(foodJSON);
for (int i = 0; i < foodArray.length(); i++) {
JSONObject foodObject = foodArray.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(COLUMN_NDB_NO, foodObject.getInt(COLUMN_NDB_NO));
values.put(COLUMN_NAME, foodObject.getString(COLUMN_NAME));
values.put(COLUMN_WATER_G, foodObject.getInt(COLUMN_WATER_G));
values.put(COLUMN_ENERGY_KCAL, foodObject.getInt(COLUMN_ENERGY_KCAL));
values.put(COLUMN_PROTEIN_G, foodObject.getInt(COLUMN_PROTEIN_G));
values.put(COLUMN_LIPID_TOT_G, foodObject.getInt(COLUMN_LIPID_TOT_G));
values.put(COLUMN_ASH_G, foodObject.getInt(COLUMN_ASH_G));
values.put(COLUMN_CARBOHYDRT_G, foodObject.getInt(COLUMN_CARBOHYDRT_G));
foodNutriProvider insert = new foodNutriProvider();
insert.insert(CONTENT_URI,values);
}
} catch (JSONException e) {
Log.e("foodSearch", "Problem parsing the earthquake JSON results", e);
Log.e("foodSearch", foodJSON);
}
foodNutriProvider getTable = new foodNutriProvider();
Cursor foodTable = getTable.query(CONTENT_URI, null, null, null, null);
return foodTable;
}
The app crashes whenever it faces an empty
field and for my app it doesn't really matter if its empty and I can give it a 0
instead.