如何从JSONArray创建游标?

9
我有一个适配器类,它扩展了GroupingCursorAdapter和构造函数类型为Adapter_Contacts(Context context, Cursor cursor, AsyncContactImageLoader asyncContactImageLoader)
我想要使用这个相同的类来填充我的ListView。我从一个Web服务中获取数据,该服务返回的是JSON格式。
因此,我的问题是:如何将JSONArray转换为Cursor以使用相同的适配器类?

1
一旦您获取了数据,就可以在列表视图中显示它。那么游标的作用是什么? - Raghunandan
我想使用与我在问题中讨论过的相同的适配器类来填充ListView,以便在应用程序中保持视图的一致性。我正在处理现有的应用程序。因此,这是必需的。 - uniruddh
但是你不能使用游标!游标只有在需要数据库时才会使用。 - Kailash Dabhi
2个回答

8
所以我的问题是,如何将JSONArray转换为Cursor以使用相同的适配器类?
您可以将该JSONArray转换为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*/});
}

0
请查看这个已准备好的方法是否有帮助:
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接