Java Android:无法解析 AsyncTask 中的方法“findViewById(int)”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20951825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:31:49  来源:igfitidea点击:

Android: cannot resolve method 'findViewById(int)' in AsyncTask

javaandroidintellij-ideaandroid-asynctask

提问by Sam Borick

Following the tutorial hereI have set up an app that should be able to download an image from a URL and place it into an ImageView. The only issue is that it cannot find findViewById because it is in the Activity class instead of the AsyncTask class. code is here:

按照此处的教程我设置了一个应用程序,该应用程序应该能够从 URL 下载图像并将其放入 ImageView。唯一的问题是它找不到 findViewById,因为它位于 Activity 类而不是 AsyncTask 类中。代码在这里:

package com.example.weather2;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class ImageDownloader
        extends AsyncTask<String, Integer, Bitmap> {
protected void onPreExecute(){
    //Setup is done here
}
@Override
protected Bitmap doInBackground(String... params) {
    //TODO Auto-generated method stub
    try{
        URL url = new URL(params[0]);
        HttpURLConnection httpCon =
                (HttpURLConnection)url.openConnection();
        if(httpCon.getResponseCode() != 200)
            throw new Exception("Failed to connect");
        InputStream is = httpCon.getInputStream();
        return BitmapFactory.decodeStream(is);
    }catch(Exception e){
        Log.e("Image", "Failed to load image", e);
    }
    return null;
}
protected void onProgressUpdate(Integer... params){
    //Update a progress bar here, or ignore it, I didn't do it
}
protected void onPostExecute(Bitmap img){
    ImageView iv = (ImageView) findViewById(R.id.imageView); //here is where the issue is
    if(iv!=null && img!=null){
        iv.setImageBitmap(img);
    }
}
protected void onCancelled(){
}
}

When I comment out the lines with the issue, I don't get any errors, which makes me think it is working, but I can't tell because there is no image being posted. Any help for solving this issue would be much appreciated.

当我注释掉问题的行时,我没有收到任何错误,这让我认为它正在工作,但我无法判断,因为没有发布图像。任何解决此问题的帮助将不胜感激。

采纳答案by Raghunandan

findViewByIdis a method of Activity class.

findViewById是Activity类的一个方法。

And you have

你有

 public class ImageDownloader
    extends AsyncTask<String, Integer, Bitmap>  // not a activity class

If you need the data back in activity you could use interface as a callback to the activity.

如果您需要活动中的数据,您可以使用接口作为活动的回调。

I would update ui in Activity itself. look @ blackbelts answer

我会在 Activity 本身中更新 ui。看看@blackbelts 的答案

How do I return a boolean from AsyncTask?

如何从 AsyncTask 返回布尔值?

Or

或者

Make AsyncTask an inner class of Activity class and update ui in onPostExecute

使 AsyncTask 成为 Activity 类的内部类并在其中更新 ui onPostExecute

Also you might find this blog by Alex Loockwood interesting

你也可能会发现亚历克斯洛克伍德的这个博客很有趣

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

回答by laalto

Instead of calling findViewById()in the AsyncTask, pass in the ImageViewas a parameter:

不是调用findViewById(),而是作为参数AsyncTask传入ImageView

public class ImageDownloader extends AsyncTask<String, Integer, Bitmap> {
    final ImageView mImageView;

    public ImageDownloader(ImageView imageView) {
        mImageView = imageView;
    }

    // ...

回答by slhddn

Use your activity directly when configuring/getting image. This will solve your problem.

配置/获取图像时直接使用您的活动。这将解决您的问题。

public class ImageDownloader extends AsyncTask<String, Integer, Bitmap> {
    private Context context;

    public ImageDownloader(Activity yourActivity) {
        context = activity;
    }

    // ...

    protected void onPostExecute(Void... params){
        ImageView iv = (ImageView) context.findViewById(R.id.imageView); 
        if(iv!=null && img!=null){
            iv.setImageBitmap(img);
        }
    }
}

回答by FrankSu

You can implement the AsyncTask as a inner class of your activity. And put ImageView iv = (ImageView) findViewById(R.id.imageView);in your activity's onCreate() method. That is what I did in my project.

您可以将 AsyncTask 实现为活动的内部类。并放入ImageView iv = (ImageView) findViewById(R.id.imageView);您的活动的 onCreate() 方法。这就是我在我的项目中所做的。

Or you can pass the activity.this as a parameter to the AsyncTask's constructor. And use ImageView iv = (ImageView)activity. findViewById(R.id.imageView)in your AsyncTask's onPostExecute() method.

或者您可以将activity.this 作为参数传递给AsyncTask 的构造函数。并ImageView iv = (ImageView)activity. findViewById(R.id.imageView)在您的 AsyncTask 的 onPostExecute() 方法中使用。

回答by Марсель Шайхин

Use cast to AppCompatActivity, such as:

使用强制转换为 AppCompatActivity,例如:

public class ImageDownloader extends AsyncTask<String, Integer, Bitmap> {
private Context context;

public ImageDownloader(Activity yourActivity) {
    context = yourActivity;
}

// ...

protected void onPostExecute(Void... params){
    //Here
    ImageView iv = (ImageView) ((AppCompatActivity) context).findViewById(R.id.imageView); 
    if(iv!=null && img!=null){
        iv.setImageBitmap(img);
    }
}

}

}