How to create Cursor from JSONArray?
Asked Answered
I

2

9

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?

Index answered 27/12, 2013 at 8:24 Comment(3)
Once you get the data you can display it in listview. What is the need for cursor?Slippage
I want to fill listview using same adapter class as i have discussed in my question to have consistency of view in application . I am working on existing application. For that this required.Index
but you cant use cursor..! cusrsor is used only when we need database..Importunate
C
8

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*/});
}
Collection answered 27/12, 2013 at 8:36 Comment(0)
S
0

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;
}
Scot answered 11/4, 2018 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.