android - 为什么加载长数据时应用程序冻结
问题描述
我在资产文件夹中有 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 的背景,所以有人可以帮忙转换它吗?
可选:如果可以增加进度并显示百分比,我会很高兴。
解决方案
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
}
推荐阅读
- caching - 如何解决 org.infinispan.commons.CacheException?
- ruby - AWS Lambda 用替换字符(U+FFFD)替换多部分格式数据附件中的某些字符
- django - Django 按外键过滤查询
- excel - 我想使用 IFS 函数检查 IF 公式
- linux - 由于 iconv 错误,我无法执行堆栈设置
- intellij-idea - 如何在 IntelliJ IDEA 中多次运行同一个项目?
- bash - 如何在 bash 中扩展表达式以获取由 ; 分隔的多个命令
- javascript - 如何使用枚举值的键定义一种对象
- reactjs - Coinmarketcap api 被 Adblock 阻止
- c# - 从具有窗口大小的 Windows 应用程序打开 URL