Question

I have an adapter class which is extending GroupingCursorAdapter and constructor of type Adapter_Contacts(Context context, Cursor cursor, AsyncContactImageLoader asyncContactImageLoader).

I want to use this same class for populating my ListView. I am getting data from one web service which is JSON.

So my question is that, how can I convert a JSONArray to Cursor to use same adapter class?

Was it helpful?

Solution

So my question is that, how can I convert a JSONArray to Cursor to use same adapter class?

You can convert that JSONArray to a MatrixCursor:

// I'm assuming that the JSONArray will contain only JSONObjects with the same propertties
MatrixCursor mc = new MatrixCursor(new String[] {"columnName1", "columnName2", /* etc*/}); // properties from the JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jo = jsonArray.getJSONObject(i);
      // extract the properties from the JSONObject and use it with the addRow() method below 
      mc.addRow(new Object[] {property1, property2, /* etc*/});
}

OTHER TIPS

PLease find this ready method helpful:

public static MatrixCursor jsonToCursor(JsonArray jsonArray) {

MatrixCursor cursor;
JsonObject jsonObject;
int jsonObjectIndex;
ArrayList<String> keys = new ArrayList<>();
ArrayList<Object> cursorRow;

keys.add("_id"); // Cursor must have "_id" column.

// Cross-list all JSON-object field names:

for (
  jsonObjectIndex = 0;
  jsonObjectIndex < jsonArray.size();
  jsonObjectIndex++) {

  jsonObject =
    jsonArray
      .get(jsonObjectIndex)
      .getAsJsonObject();

      for (String key : jsonObject.keySet()) {
        if (!keys.contains(key)) {
          keys.add(key);
        }
      }
}

// Set CURSOR-object column names:

cursor =
  new MatrixCursor(
    (String[]) keys.toArray());

for (
  jsonObjectIndex = 0;
  jsonObjectIndex < jsonArray.size();
  jsonObjectIndex++) {

  jsonObject =
    jsonArray
      .get(jsonObjectIndex)
      .getAsJsonObject();

  // Create CURSOR-object row:

  cursorRow = new ArrayList<>();

  for (String key : keys) {

    cursorRow.add(
      jsonObject.get(
        key));
  }

  cursor.addRow(
    cursorRow);
}

return cursor;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top