我得到以下ArrayoutofBound例外:ArrayIndexOutofBoundException當第二個值是不存在的JSON解析
Process: com.lifeontrack, PID: 1379
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
at com.lifeontrack.fragment.caregiver.ViewCaregiverFragment$3.onResponse(ViewCaregiverFragment.java:154)
at com.lifeontrack.fragment.caregiver.ViewCaregiverFragment$3.onResponse(ViewCaregiverFragment.java:126)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
代碼:
String numberone = "";
String numbertwo = "";
JSONArray phoneArray = jsonObject.getJSONArray("phone");
JSONObject cit = phoneArray.getJSONObject(0);
String phoneNumbers = "";
for (int count=1; count <= phoneArray.length(); count++)
{
if (phoneNumbers.length() == 0)
phoneNumbers += phoneArray.getJSONObject(count-1).getString("value");
else
phoneNumbers += ","+ phoneArray.getJSONObject(count-1).getString("value");
}
System.out.println("Phonenumbers" + phoneNumbers);
String[] numbers = phoneNumbers.split(",");
numberone = numbers[0];
numbertwo = numbers[1];
View.setText(numberone);
View.setText(numbertwo);
Button btn_home_phone_viewCg = ((Button) rootView.findViewById(R.id.btn_home_phone_viewCg));
btn_home_phone_viewCg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!Objects.equals(numberone, "")){
Uri numberoneuri = Uri.parse("tel:"+numberone);
Intent callIntent = new Intent(Intent.ACTION_DIAL, numberoneuri);
startActivity(callIntent);
}
}
});
Button btn_home_phone_viewCgtwo = ((Button) rootView.findViewById(R.id.btn_home_phone_viewCgtwo));
btn_home_phone_viewCgtwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!Objects.equals(numbertwo, "")){
Uri numbertwouri = Uri.parse("tel:"+numbertwo);
Intent callIntent = new Intent(Intent.ACTION_DIAL, numbertwouri);
startActivity(callIntent);
}
}
});
當代碼運行輸出:Phonenumbers : 9784513234,9487516132
當代碼打破輸出:Phonenumbers : 9784513234,
我相信當String「numbertwo」沒有值的時候會發生這種情況,這可能嗎?如果是的話如何處理這種情況?
檢查你的JSON所得到的響應,bcoz WRT代碼它應該工作... –