onCreate 方法中的 AsyncTask 和 setAdapter

发布于 2024-10-02 00:37:21 字数 593 浏览 3 评论 0原文

我正在做一些繁重的网络任务 - 下载图片(预览) - 为了不阻止我的主 UI,它在 AsyncTask 中执行了此操作,我想将它们放入 GridView 中,但我在 AsyncTask 完成之前设置了适配器。一些代码会更有帮助

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.gridview);
            new LoadAllPictures().execute();
            GridView g = (GridView) findViewById(R.id.gridview);
            g.setAdapter(new ImageAdapter(this));
}

所以最后 Logcat 显示所有内容都已下载,但我的屏幕上什么也没有。 我尝试在 AsyncTask 中执行 setAdapter 部分,但它告诉我:只有创建视图层次结构的原始线程才能触摸其视图。

我应该做什么?

I am doing some heavy network tasks - downloading pictures (previews) -
For my main UI to not be blocked it did that in an AsyncTask, I want to put them in a GridView but I set the adapter before the AsyncTask finishes. Some code will be more helpfull

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.gridview);
            new LoadAllPictures().execute();
            GridView g = (GridView) findViewById(R.id.gridview);
            g.setAdapter(new ImageAdapter(this));
}

So at the end the Logcat shows that everything had been dowloaded but nothing on my screen.
I tried doing the setAdapter part in my AsyncTask but it tells me that: Only the original thread that created a view hierarchy can touch its views.

What should I do ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神魇的王 2024-10-09 00:37:21

AsyncTask 有一个有用的方法,您可以实现名为 onPostExecute()。任务完成后从原始 UI 线程调用它。您可以使用它从正确的线程设置适配器。

AsyncTask has a useful method you can implement named onPostExecute(). It's called from the original UI thread after the task has completed. You can use it to set the adapter from the correct thread.

暗恋未遂 2024-10-09 00:37:21

AsyncTask有3个基本方法:

protected void onPreExecute()
{
}

protected void onPostExecute(Void unused)   
{
  // displaying images
  // set adapter for listview with downloaded items
}

protected Void doInBackground(Void... params) 
{
     // downloading and time consuming task 
}

所以可以在onPostExecute(Voidused)方法里面写g.setAdapter(new ImageAdapter(this));,因为此时图片已在 doInBackground() 方法中下载。

AsyncTask has 3 basic methods:

protected void onPreExecute()
{
}

protected void onPostExecute(Void unused)   
{
  // displaying images
  // set adapter for listview with downloaded items
}

protected Void doInBackground(Void... params) 
{
     // downloading and time consuming task 
}

so you can write g.setAdapter(new ImageAdapter(this)); inside the onPostExecute(Void unused) method because at this time, the pictures are already downloaded inside the doInBackground() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文