【问题标题】:drawable from an url with honeycomb可从带有蜂窝的 url 绘制
【发布时间】:2011-06-30 23:38:17
【问题描述】:

从一开始我就使用这种方法:

 public Drawable createPortrait(String url){
    try {
        InputStream is = (InputStream)new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "Image");
        return d;
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

}

但是honeycomb 不允许我再这样做了,我在日志中看到的是:android.os.networkonmainthreadexception。 问题是我的 url 已经取自 json 数据:

 private class GrabURL extends AsyncTask<String, Void, Void> {
    private final HttpClient Client = new DefaultHttpClient();
    private String Content;
    private String Error = null;
    private ProgressDialog Dialog = new ProgressDialog(Main.this);

    protected void onPreExecute() {
        Dialog.setMessage("Downloading source..");
        Dialog.show();
    }

    protected Void doInBackground(String... urls) {
        try {
            HttpGet httpget = new HttpGet(urls[0]);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            Content = Client.execute(httpget, responseHandler);
        } catch (ClientProtocolException e) {
            Error = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            Error = e.getMessage();
            cancel(true);
        }

        return null;
    }
    protected void onPostExecute(Void unused) {
        Dialog.dismiss();
        if (Error != null) {
            Toast.makeText(Main.this, Error, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(Main.this, "Source: " + Content, Toast.LENGTH_LONG).show();
        }
        Object o = new Gson().fromJson(Content, Info.class);
        Info i = (Info)o;
        String d = i.getData().get(0).getLg_portrait();
        portrait.setBackgroundDrawable(createPortrait(d));
    }

}

并且 Portrait 是一个 ImageView 。我不知道该怎么办。

【问题讨论】:

    标签: java android json image android-asynctask


    【解决方案1】:

    您还需要在异步任务中下载图像。 Honeycomb 根本不会让您运行冗长的 HTTP 操作阻塞 UI 线程(从流中读取会进行 HTTP 调用并等待下载图像)。您应该立即返回一些占位符,触发 AsyncTask 并在图像已下载后替换它。

    提示“执行后”在 UI 线程中运行....

    【讨论】:

    • 在代码中会是什么?我不明白你所说的“占位符”是什么意思。
    • 占位符图像(否则显示空白) - 它可能是动画进度指示器。您必须将 createPortrait(d) 从 onPostExecute()(UI 线程)移至 doInBackground()(后台线程)。
    • 好的,但我必须创建另一个私有类,如graburl;
    猜你喜欢
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多