Try-Catch JSON 数组空指针什么也没捕获
Try-Catch JSONArray Nullpointer catch nothing
如果 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 或其他方法来防止应用程序崩溃吗?
谢谢:-)
如果 jsonArray
为空,您可以在 for 之前检查或为 Null Pointer 添加一个新的 catch
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject customer = jsonArray.getJSONObject(i);
...
} catch (JSONException e) {
return;
} catch (NullPointerException npe) {
//do something
}
如果 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 或其他方法来防止应用程序崩溃吗? 谢谢:-)
如果 jsonArray
为空,您可以在 for 之前检查或为 Null Pointer 添加一个新的 catch
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject customer = jsonArray.getJSONObject(i);
...
} catch (JSONException e) {
return;
} catch (NullPointerException npe) {
//do something
}