虽然我在网上查了很多参考文献,但我仍然找不到问题。
似乎ProgressDialog
看起来不错,但每当我想要更新进度时,在onProgressUpdate
中它的实例总是为空。
这是我的AsyncTask
:
package com.async_tasks;
public class UploadTask extends AsyncTask<Void,Integer,Void> implements Serializable {
private static final String TAG = UploadTask.class.getSimpleName();
private ConnectionToServer _connectionToServer;
private TransferDetails _td;
private Activity _activity;
private ProgressDialog _progDialog;
private UploadTask _taskInstance;
public UploadTask(Activity activity, ConnectionToServer connectionToServer, TransferDetails td) {
_activity = activity;
_connectionToServer = connectionToServer;
_td = td;
_taskInstance = this;
}
@Override
protected void onPreExecute() {
_progDialog = new ProgressDialog(_activity);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}
@Override
protected Void doInBackground(Void... voids) {
//uploading file ...
float percent = (float) (fileSize - bytesToRead) / fileSize * 100;
publishProgress((int)percent);
}
}
catch (IOException e) {
// Handling exception
} finally {
if(bis!=null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
clearMembers();
}
}
return null;
}
@Override
protected void onProgressUpdate(Integer... progress) {
if(_progDialog!=null) { // <<------------ I suspect for some reason this is always false, as _progDialog is always null - But why?!
_progDialog.incrementProgressBy(progress[0]);
}
}
@Override
protected void onPostExecute(Void result) {
//The task is complete, clear members
clearMembers();
}
private void clearMembers() {
_activity = null;
if(_progDialog!=null) {
_progDialog.dismiss();
_progDialog = null;
}
}
}
这是来自MainActivity
的电话:
TransferDetails td = (TransferDetails) report.data();
ConnectionToServer conn = StorageServerProxyService.getConn();
UploadTask uploadTask = new UploadTask(MainActivity.this, conn, td);
uploadTask.execute();
答案 0 :(得分:0)
修改onPreExecute()方法,如下所示:
@Override
protected void onPreExecute() {
progDialog = new ProgressDialog(ActivityName.this);
String cancel = _context.getResources().getString(R.string.cancel);
_progDialog.setCancelable(false);
_progDialog.setTitle(_context.getResources().getString(R.string.uploading));
_progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
_progDialog.setProgress(0);
_progDialog.setMax(100);
_progDialog.setButton(DialogInterface.BUTTON_NEGATIVE, cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
_taskInstance.cancel(true);
}
});
_progDialog.show();
}