可以从带蜂窝的网址中抽出

时间:2011-06-30 23:38:18

标签: java android json image android-asynctask

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

 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;
    }

}

但是蜂窝不允许我再这样做了,我在日志中看到的是:android.os.networkonmainthreadexception。 问题是我的网址已经从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));
    }

}

和肖像是一个ImageView。我不知道该怎么做。

1 个答案:

答案 0 :(得分:0)

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

提示“post execute”在UI线程中运行....