プログレスバーの作成方法を学ぶために、このチュートリアルに従っています。アクティビティの上に進行状況バーを表示し、バックグラウンドでアクティビティのテーブル ビューを更新しようとしています。
そこで、コールバックを受け取るダイアログの非同期タスクを作成しました。
package com.lib.bookworm;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class UIThreadProgress extends AsyncTask<Void, Void, Void> {
private UIThreadCallback callback = null;
private ProgressDialog dialog = null;
private int maxValue = 100, incAmount = 1;
private Context context = null;
public UIThreadProgress(Context context, UIThreadCallback callback) {
this.context = context;
this.callback = callback;
}
@Override
protected Void doInBackground(Void... args) {
while(this.callback.condition()) {
this.callback.run();
this.publishProgress();
}
return null;
}
@Override protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
dialog.incrementProgressBy(incAmount);
};
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setCancelable(true);
dialog.setMessage("Loading...");
dialog.setProgress(0);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setMax(maxValue);
dialog.show();
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
this.callback.onThreadFinish();
}
}
マイ アクティビティで:
final String page = htmlPage.substring(start, end).trim();
//Create new instance of the AsyncTask..
new UIThreadProgress(this, new UIThreadCallback() {
@Override
public void run() {
row_id = makeTableRow(row_id, layout, params, matcher); //ADD a row to the table layout.
}
@Override
public void onThreadFinish() {
System.out.println("FINISHED!!");
}
@Override
public boolean condition() {
return matcher.find();
}
}).execute();
したがって、上記は、実行された作業量を示す進行状況バーを表示しながら、テーブル レイアウト アクティビティを更新するために実行する非同期タスクを作成します。
ただし、アクティビティを開始したスレッドのみがそのビューを更新できるというエラーが表示されます。Async Task の実行を次のように変更してみました。
MainActivity.this.runOnUiThread(new Runnable() {
@Override public void run() {
row_id = makeTableRow(row_id, layout, params, matcher); //ADD a row to the table layout.
}
}
しかし、これにより同期エラーが発生します.進行状況を表示し、同時にバックグラウンドでテーブルを更新する方法はありますか?
現在、私のUIは次のようになっています: