我在资产文件夹中有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。但是,您可以使用线程(例如:
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
}
而不是创建新线程,您必须使用AsyncTask类它是用于Android后台任务的特殊类。你的代码片段可能就像下面一样。
创建一个名为FileReadAsyncTask的新类
public class FileReadAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
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();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
@Override
protected void onCancelled(Void result) {
super.onCancelled(result);
}
}
然后从MainActivity或其他类调用
new FileReadAsyncTask ().execute((Void) null);