mahdi pishguy mahdi pishguy - 1 month ago 6
Android Question

Android create JsonArrays with JsonObject content

I'm trying to create simple

JsonArray
with some
JsonObject
with some mobile numbers, when i try to create this as

["data":{"contactName":"xxxxx", "mobileNumber":"0000}]


format into
while


my json object length is
1
, i checked while statement and its work fine without any problem but each put data on json object replaced and length is
1


public static JSONArray getLocalContactsList(ContentResolver cr) throws JSONException {

JSONArray contacts = new JSONArray();
JSONObject contact = new JSONObject();

Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (phones.moveToNext()) {
final String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phone_number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phone_number = phone_number.replaceAll("\\s+", "").trim();
phone_number = phone_number.replace("-", "").trim();

if (phone_number.startsWith("+")) {
phone_number = phone_number.substring(3, phone_number.length());
phone_number = "0" + phone_number;
}
if (phone_number.startsWith("0")) {
JSONObject c = new JSONObject();
c.put("contactName", name);
c.put("mobileNumber", phone_number);
contact.put("data", c);
}
}
contacts.put(contact);
phones.close();
return contacts;
}


problem is this part of code:

JSONObject c = new JSONObject();
c.put("contactName", name);
c.put("mobileNumber", phone_number);
contact.put("data", c);

Answer

The problem is that you add a contact to JSONArray only once after the loop finished processing all items. Just move contacts.put(contact); into a loop, like that:

while (phones.moveToNext()) {
    final String name         = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String       phone_number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    phone_number = phone_number.replaceAll("\\s+", "").trim();
    phone_number = phone_number.replace("-", "").trim();

    if (phone_number.startsWith("+")) {
        phone_number = phone_number.substring(3, phone_number.length());
        phone_number = "0" + phone_number;
    }
    if (phone_number.startsWith("0")) {
        JSONObject c = new JSONObject();
        c.put("contactName", name);
        c.put("mobileNumber", phone_number);
        contact.put("data", c);
    }
    // the next line should be inside the loop
    contacts.put(contact);
}

This should fix the bug, but not the whole problem, as was pointed out by npace. Consider using GSON library that will handle the task of converting stuff to JSONObjects or JSONArrays