英文:
Cannot access ProgressBar from AsyncTask
问题
class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... genx) {
while (...) {
publishProgress((int)(total * 100 / filelen));
}
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mPB.setProgress(progress[0]);
}
...
}
public class MainActivity extends AppCompatActivity {
ProgressBar mPB;
protected void onCreate(Bundle savedInstanceState) {
mPB = (ProgressBar) findViewById(R.id.progressBar1);
}
}
英文:
I got a simple application that downloads a file. But I cannot access the ProgressBar decared in MainActivity from AsyncTask class. The code is:
class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
protected Long doInBackground(String... genx) {
while(...) {
publishProgress((int)(total * 100 / filelen));
}
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mPB.setProgress(progress[0]);
}
...
}
public class MainActivity extends AppCompatActivity {
ProgressBar mPB;
protected void onCreate(Bundle savedInstanceState) {
mPB = (ProgressBar) findViewById(R.id.progressBar1);
}
}
答案1
得分: 1
将您的 ProgressBar
传递给构造函数 DownloadFilesTask
class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
private ProgressBar mPB;
DownloadFilesTask(ProgressBar mPB) {
this.mPB = mPB;
}
protected Long doInBackground(String... genx) {
while(...) {
publishProgress((int)(total * 100 / filelen));
}
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mPB.setProgress(progress[0]);
}
// ...
}
英文:
Pass your ProgressBar
in constructer DownloadFilesTask
class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
private ProgressBar mPB;
DownloadFilesTask(ProgressBar mPB) {
this.mPB = mPB;
}
protected Long doInBackground(String... genx) {
while(...) {
publishProgress((int)(total * 100 / filelen));
}
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mPB.setProgress(progress[0]);
}
...
}
答案2
得分: -1
你在onCreate(...)中没有调用setContentView(...)。
英文:
You didn't call setContentView(..) in onCreate(...)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论