【问题标题】:How to read Json from online instead of asset folder如何从在线而不是资产文件夹中读取 Json
【发布时间】:2020-01-09 02:07:32
【问题描述】:

我正在学习从在线制作测验应用程序,并且进展顺利。我想知道,与其从 assets 中读取 json ,不如从网上读取这样可以添加或相应更改问题并且用户不必更新 app.

这是 JSON 结构。

{"questions" : [{"category":"general","question": "Grand Central Terminal, Park Avenue, New York is the world's", "choices": ["largest railway station","highest railway station","longest railway station","None of the above"], "correctAnswer":0},
    {"category":"science","question": "Entomology is the science that studies", "choices": ["Behavior of human beings","Insects","The origin and history of technical and scientific terms","the formation of rocks"], "correctAnswer":1},

    {"category":"science", "question":"What is known as the 'master gland' of the human body?", "choices":["Thyroid gland","Pituitary gland","Pineal gland","Pancreas"],"correctAnswer":1}
  ]}

从资产中读取的代码是

    private String loadJSONFromAsset() {
        String json = null;
        try {
            InputStream is = mContext.getAssets().open("questionsJSON.json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();
            json = new String(buffer, "UTF-8");
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;
    }

我想在下一个问题加载时显示进度加载对话框,我们将不胜感激。提前致谢。

【问题讨论】:

  • 下载 json 文本内容应该与下载任何其他文本上下文没有什么不同 - 你尝试过什么?

标签: java android json


【解决方案1】:

最好的选择是使用REST APIs,从服务器/数据库获取数据,可以随时随地编辑

你可以学习使用Node js,不难,它是基于JavaScript的。

要从 API 获取 JSON,您可以使用 Retrofit

如果您是初学者,学习和实施这些东西会有点困难,但从长远来看,这将是最佳选择

希望这有帮助!

【讨论】:

    【解决方案2】:

    也许考虑使用两个不同的线程(或 Runnables),一个线程用于下载 JSON 内容,另一个线程用于显示 GUI。例如,看看这个:Stackoverflow Post

    解决方案涉及制作一个 Runnable,它首先开始从在线网站下载数据,然后在下载时将当前进度更新到 GUI 线程。他使用BufferedInputStream 类,因此他可以使用while 循环来读取数据,更新下载的字节数,获取当前进度,然后显示结果。我想你可以在这里使用一个while循环来做类似的事情,然后检查下载是否完成。如果是这样,您可以关闭显示。

    【讨论】:

      猜你喜欢
      • 2020-10-16
      • 2020-11-27
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      相关资源
      最近更新 更多