无法从AsyncTask访问ProgressBar。

huangapple go评论62阅读模式
英文:

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&lt;String, Integer, Long&gt; {

    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&lt;String, Integer, Long&gt; {

    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(...)

huangapple
  • 本文由 发表于 2020年10月10日 02:21:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64285375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定