Android的:不能在AsyncTask的解决方法“findViewById(int)的' [英] Android: cannot resolve method 'findViewById(int)' in AsyncTask
问题描述
继教程 我已成立一个应用程序应该能够从一个URL下载图像,并把它变成一个ImageView的。唯一的问题是,它无法找到findViewById,因为它是在活动类,而不是AsyncTask的类。 code是在这里:
Following the tutorial here I 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:
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(){
}
}
在我行注释掉这个问题,我没有得到任何错误,这让我觉得这是工作,但我不能说,因为没有被张贴的形象。
解决这个问题的任何帮助将非常AP preciated。
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.
推荐答案
findViewById
是Activity类的方法。
findViewById
is a method of Activity class.
和你有
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.
我将更新活动本身的UI。看看@ blackbelts回答
I would update ui in Activity itself. look @ blackbelts answer
或者
请AsyncTask的一个内部类Activity类和更新UI的 onPostExecute
Make AsyncTask an inner class of Activity class and update ui in onPostExecute
您也可以由Alex Loockwood发现这个有趣的博客
Also you might find this blog by Alex Loockwood interesting
的http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
这篇关于Android的:不能在AsyncTask的解决方法“findViewById(int)的'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!