【问题标题】:Receiving image in Asynctask and display it in ImageView在 Asynctask 中接收图像并在 ImageView 中显示
【发布时间】:2016-02-28 15:11:39
【问题描述】:

我正在尝试通过 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'
} }

【问题讨论】:

    标签: android tcp android-asynctask imageview


    【解决方案1】:

    看起来DownloadImageTask 类不是TcpClient 扩展Activity 类的inner-class,所以要访问其他类中ImageView 的imageView 对象,需要使用相同的类构造函数将其发送到DownloadImageTask就像目前在 DownloadImageTask 类中获取 Host 和 SocketIn 一样。

    DownloadImageTask改成使用imageView"

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

    【讨论】:

    • 感谢您的解决方案,但是接收的想法是否正确,下一步是否会通过TCP重复接收图像并显示它?
    • @Se-BASS-tian: 是的,正确,因为图像 src 数据是通过 TCP 接收的,而不是 ImageView,其中想要显示通过 TCP 接收的数据
    猜你喜欢
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    • 2019-02-17
    • 2015-03-20
    • 2015-11-09
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多