【问题标题】:Confusion about Asyntask while retrieving image检索图像时对 Asyntask 的困惑
【发布时间】:2014-03-27 14:15:37
【问题描述】:

我试图从互联网上检索图像并找到类似的示例,然后稍微更改了我找到的代码。但是当我运行我的代码时,我得到了这个异常android.os.NetworkOnMainThreadException。然后我搜索了解决方案并注意到我应该使用@ 987654322@ 这样做的类。问题很简单,我只是无法在每一行代码中都出现语法错误。请您帮助如何修复此代码并使其正常运行。提前致谢

class BackroundActivity extends AsyncTask<Void, Bitmap, Void>
{

    @Override
    protected Bitmap doInBackground(String src) throws IOException {
        HttpURLConnection con = null;

            URL url=new URL(src);
            con=(HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            InputStream input=con.getInputStream();
            Bitmap bmp=BitmapFactory.decodeStream(input);
            return bmp;

    }

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    AsyncTask 使用的是varargs,而且你没有正确指定返回类型,所以正确的代码如下:

    class BackroundActivity extends AsyncTask<String, Void, Bitmap>
    {
    
        @Override
        protected Bitmap doInBackground(String... src) throws IOException {
            HttpURLConnection con = null;
    
            URL url=new URL(src[0]);
            con=(HttpURLConnection) url.openConnection();
            InputStream input=con.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(input);
            return bmp;
    
        }
    }
    

    来自docs

    异步任务使用的三种类型如下:

    1. Params,执行时发送给任务的参数类型。
    2. 进度,在后台计算期间发布的进度单元的类型。
    3. Result,后台计算结果的类型。

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 2021-10-28
      • 1970-01-01
      • 2019-03-14
      • 2016-02-10
      • 1970-01-01
      • 2017-06-11
      • 2014-11-03
      相关资源
      最近更新 更多