首页 > 解决方案 > 为什么加载长数据时应用程序冻结

问题描述

我在资产文件夹中有 JSON 本地文件,如下所示,但超过 10,000 个对象,当我阅读它们时,它需要 40 多秒并冻结应用程序,所以有人可以解释我如何在 Asynctask 中做到这一点吗?

{
  "status": true,
  "result": [
    {
      "id": 22,
      "name": "T........",
    }
  ]
}

代码

try {
            InputStream inputStream = getAssets().open("LocalTest.json");
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            inputStream.close();
            String Categories = new String(buffer, "UTF-8");
            JSONObject jsonObject = new JSONObject(Categories);
            for (int x = 0; x < jsonObject.getJSONArray("result").length(); x++) {
                //Put data in array
            }
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

我没有任何 Asynctask 的背景,所以有人可以帮忙转换它吗?

可选:如果可以增加进度并显示百分比,我会很高兴。

标签: android

解决方案


Asynctask 现在已弃用。但是,您可以使用 Thread 例如:

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);
    readJSON();
}

private void readJSON() {
    new Thread(new Runnable() {
        public void run() {
            try {
                InputStream inputStream = getAssets().open("LocalTest.json");
                byte[] buffer = new byte[inputStream.available()];
                inputStream.read(buffer);
                inputStream.close();
                String Categories = new String(buffer, "UTF-8");
                JSONObject jsonObject = new JSONObject(Categories);
                for (int x = 0; x < jsonObject.getJSONArray("result").length(); x++) {
                    //Put data in array
                }
                onReadJSONFinished();
            } catch (JSONException | IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

private void onReadJSONFinished() {
    // Do what you want when your data is loaded
}

推荐阅读