开发者

drawable from an url with honeycomb

from the beginning i used this method :

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

}

but honeycomb doesn't allow me to do it anymore, what i see in my log is : android.os.networkonmainthreadexception . the thing is that my url is already taken from json data :

 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 BasicRe开发者_高级运维sponseHandler();
            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));
    }

}

and portrait is an ImageView . i don't know what to do .


You need to download the image in Async task as well. Honeycomb simply does not let you run lengthy HTTP operation blocking the UI thread (reading from stream makes HTTP call and waits for the image to be downloaded). You should return some placeholder immediately, trigger AsyncTask and replace the image after it is already downloaded.

Hint "post execute" is run in UI thread....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜