我正在加载日志数据。它运行顺利。但是,我在工具栏下面添加了一个不确定的进度条,每次调用Asynctask时都会显示。
thread.sleep
吗? 这是我的代码:
public void refreshList(String status) {
String id = String.valueOf(getArguments().getInt("ID"));
String paramsValue[] = new String[2];
paramsValue[0] = id;
paramsValue[1] = status;
new LogsTask(this).execute(paramsValue);
}
private static class LogsTask extends AsyncTask<String[], Integer, LinkedHashMap<Integer, ValuesExtension>> {
String paramsValue[];
LogsFragment logsFragment;
WeakReference<LogsFragment> fragmentWeakReference;
LogsTask(LogsFragment logsFragment) {
fragmentWeakReference = new WeakReference<>(logsFragment);
}
@Override
protected void onPreExecute() {
logsFragment = fragmentWeakReference.get();
logsFragment.pbLogs.setVisibility(View.VISIBLE);
}
@Override
protected LinkedHashMap<Integer, ValuesExtension> doInBackground(String[]... params) {
Cursor dbReader = null;
DBHelper dbHelper = new DBHelper(logsFragment.getContext());
LinkedHashMap<Integer, ValuesExtension> logsMap = new LinkedHashMap<>();
try {
dbHelper.open();
if (dbReader.getCount() > 0) {
while (dbReader.moveToNext()) {
try {
/* LOADING OF DATA */
logsMap.put("values", value);
Thread.sleep(250); // is this important when loading data?
} catch (InterruptedException | ParseException e) {
e.printStackTrace();
}
}
}
} catch (SQLException e) {
return null;
} finally {
if (dbReader != null) {
dbReader.close();
}
dbHelper.close();
}
return logsMap;
}
@Override
protected void onPostExecute(LinkedHashMap<Integer, ValuesExtension> logsMap) {
logsFragment.pbLogs.setVisibility(View.GONE);
if (logsMap != null) {
logsFragment.refreshLog();
}
}
}
答案 0 :(得分:1)
作为一种解决方法,您可以将进度条的开始延迟300毫秒,具体取决于数据的加载速度
private boolean completed = false;
@Override
protected void onPreExecute() {
logsFragment = fragmentWeakReference.get();
//below code won't display progress if your task completes within 300 ms and longer tasks it will be shown after 300 ms
logsFragment.pbLogs.postDelayed(new Runnable(){
@Override
public void run(){
if(!completed)
logsFragment.pbLogs.setVisibility(View.VISIBLE);
}, 300);
}
@Override
protected void onPostExecute(LinkedHashMap<Integer, ValuesExtension> logsMap) {
completed = true;
logsFragment.pbLogs.setVisibility(View.GONE);
if (logsMap != null) {
logsFragment.refreshLog();
}
}