如果jsonarray是空的,我想什么都不抓。这是我的代码:
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject customer = jsonArray.getJSONObject(i);
int sender = customer.getInt("sender");
Log.e("Customer", "is " + jsonArray.getJSONObject(i));
TextView tv[] = new TextView[jsonArray.length()];
tv[i] = new TextView(ChatActivity.this);
Log.i("Sender", "is " + sender);
// Log.i("Curernt ID", "is " + currentUserId);
// Log.i("Logged in", " ID is " + sharedPrefsUser.getInt(SharedPrefsInformation.ID_FROM_LOGGED_IN_USER, -1));
// Log.i("")
if (sharedPrefsUser.getInt(SharedPrefsInformation.ID_FROM_LOGGED_IN_USER, -1) == sender) {
tv[i] = (TextView) getLayoutInflater().inflate(R.layout.messae, null);
} else {
tv[i] = (TextView) getLayoutInflater().inflate(R.layout.message_other, null);
}
tv[i].setText(customer.getString("message"));
Log.e("Message", "is " + customer.getString("message"));
linearLayoutWithMessages.addView(tv[i]);
}
} catch (JSONException e) {
return;
}
但是现在应用程序将崩溃,因为jsonArary是空的(Nullpointer)。 任何建议,致电Toast或其他东西,以防止应用程序崩溃? 谢谢: - )
答案 0 :(得分:1)
您可以在for之前检查jsonArray
是否为空或为Null Pointer添加新的捕获
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject customer = jsonArray.getJSONObject(i);
...
} catch (JSONException e) {
return;
} catch (NullPointerException npe) {
//do something
}