“这是将数据转换成json格式的代码”
private void jsonformatdata() {
// TODO Auto-generated method stub
JSONArray arr = new JSONArray();
try {
for(int i=0;i<=contactModel.size();i++)
{
JSONObject jsonAdd = new JSONObject();
jsonAdd.put("strModifiedDate", localTime);
jsonAdd.put("contactName", contactModel.get(i).getPhonebookName());
jsonAdd.put("uniqueContactID", contactModel.get(i).getContactId());
JSONArray phone = new JSONArray();
if(contactModel.get(i).getHomeNummber() == null)
{}
else
{JSONObject num1 = new JSONObject();
num1.put("",contactModel.get(i).getHomeNummber());
phone.put(num1);}
if(contactModel.get(i).getMobileNummber()==null)
{}
else
{JSONObject num2 = new JSONObject();
num2.put("",contactModel.get(i).getMobileNummber());
phone.put(num2);}
if(contactModel.get(i).getWorkNummber()==null){}
else{JSONObject num3 = new JSONObject();
num3.put("",contactModel.get(i).getWorkNummber());
phone.put(num3);}
if(contactModel.get(i).getOtherNummber()==null){}
else{JSONObject num4 = new JSONObject();
num4.put("",contactModel.get(i).getOtherNummber());
phone.put(num4);}
jsonAdd.put("phone",phone);
arr.put(i,jsonAdd);
}
String datatosend = arr.toString();
Log.e(datatosend, ""+datatosend);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我在 logcat 中得到的错误信息
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.vchat/com.example.vchat.Friends_listing}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
最佳答案
您需要转换:
for(int i=0;i<=contactModel.size();i++)
到:
for(int i=0;i<contactModel.size();i++)
数组中的元素从零开始直到大小。可能是你的 contactModel
是空的。
此外,下次请在问题中包括完整的堆栈跟踪(如果有的话)。
关于java - 我正在从手机获取联系人详细信息,当我尝试转换为 json 格式时,应用程序崩溃了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33516739/