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?

3
  • 1
    Once you get the data you can display it in listview. What is the need for cursor? Commented Dec 27, 2013 at 8:28
  • 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. Commented Dec 27, 2013 at 8:30
  • but you cant use cursor..! cusrsor is used only when we need database.. Commented Dec 27, 2013 at 8:36

2 Answers 2

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*/});
}
Sign up to request clarification or add additional context in comments.

Comments

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.