如何将JSON数据从资产文件夹加载到Recyclerview中

时间:2019-08-15 16:17:10

标签: android json sqlite android-studio android-recyclerview

我被困在RecyclerView中的数据中。我在像这样的资产文件夹中有一个json:

json data

我想将此数据加载到我的RecyclerView和CardView中。我已经阅读了许多教程,但是没有关于我的案例的教程。每个RecyclerView教程都会始终从互联网上加载JSON。

1 个答案:

答案 0 :(得分:0)

首先,您正在尝试一步一个脚印。您很少会在一处为您的特定问题找到解决方案。解决问题的最佳方法是将其分为较小的问题。 例如,如果我们接受您的问题,可以将其分为以下几个部分:

  1. 读取资产文件夹中的文件
  2. 将文件数据解析为json
  3. 从json提取数据
  4. 将适配器中的数据用于recyclerview

在这4部分中,您应该已经知道第四部分,因此现在您需要查找前3部分。 如果您在Google的每个部分上进行搜索,都会发现每个部分都有很多答案。

1。读取资产文件夹中的文件

以下功能将为您提供 String 中的文件内容:

 private String getFileContentsAsString(Context context, String file)
    {
        String str = "";
        try
        {
            AssetManager assetManager = context.getAssets();
            InputStream in = null;
            try {
                in = assetManager.open(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            InputStreamReader isr = new InputStreamReader(in);
            char [] inputBuffer = new char[100];

            int charRead;
            while((charRead = isr.read(inputBuffer))>0)
            {
                String readString = String.copyValueOf(inputBuffer,0,charRead);
                str += readString;
            }
        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }

        return str;
    }

2。将文件数据解析为json
现在您已将数据作为字符串,可以将其解析为JSON:

          String fileString = getFileContentsAsString("contents.json");
          JSONObject  json = new JSONObject(fileString);

3。从json提取数据
获取json数组,然后将数据映射到您自己的对象上。

          JSONArray itemArray = json.getJSONArray("items");

4。在适配器中使用数据
使用上述步骤中的数据填充适配器。

同样,所有这些步骤的资源已经在那里。