在Asynctask中接收图像并在ImageView中显示它

时间:2015-11-25 17:42:07

标签: android tcp android-asynctask imageview

我尝试通过TCP接收图像(在Asynctask中)并在ImageView中显示它,但我在onPostExecute中有错误。谁知道为什么?

还有接收的想法是否正确,下一步是否会重复通过TCP接收图像并显示它?

代码:

public class TcpClient extends Activity  {

ImageView imageView;

public static String aHost;
public String aSocketIn;

public static int aSocketInInt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bundle_result);

    imageView = (ImageView) findViewById(R.id.imageView);

    Intent intent = getIntent();

        aHost = intent.getStringExtra("addressIp");
        aSocketIn = intent.getStringExtra("socketIn");

    aSocketInInt = Integer.parseInt(aSocketIn);


    new DownloadImageTask(aHost,aSocketInInt).execute();   
} }

public class DownloadImageTask extends AsyncTask <Void,Void,Bitmap > {

public Bitmap bitmap = null;
String Host;
int SocketIn;

public  DownloadImageTask(String Host,int SocketIn) {
        this.Host = Host;
        this.SocketIn = SocketIn;
}

@Override
protected Bitmap doInBackground(Void... params) {

    ClientIn clientIn;

    try {
        InetAddress serwerAddress = InetAddress.getByName(Host);
        Socket socket = new Socket(serwerAddress, SocketIn);
        clientIn = new ClientIn(socket);
        bitmap = clientIn.Receive();
        return bitmap;
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

@Override
protected void onPostExecute(Bitmap result) {    

    imageView.setImageBitmap(result);  // ERROR: Cannot resolve symbol 'imageView'
} }

1 个答案:

答案 0 :(得分:1)

看起来DownloadImageTask类不是inner-classTcpClient正在扩展Activity,所以要在其他类中访问ImageView的imageView对象,需要发送它DownloadImageTask使用类构造函数的方式与当前在SocketIn类中获取Host和DownloadImageTask的方式相同。

DownloadImageTask更改为使用imageView

public  DownloadImageTask(String Host,int SocketIn,ImageView imageView) {
        this.Host = Host;
        this.SocketIn = SocketIn;
        this.imageView=imageView;
}