当前位置: 动力学知识库 > 问答 > 编程问答 >

Android : Device 2.3.3 work well. But Device 4.0.3 don't work. Load Image

问题描述:

Android : Device 2.3.3 work well. But Device 4.3 ( HTC One), 4.2.2 don't work. Load Image

'public static Bitmap getBitmapFroUrl(String url) {

 URL m;

InputStream i = null;

BufferedInputStream bis = null;

ByteArrayOutputStream out =null;

try {

m = new URL(url);

URLConnection connection = m.openConnection();

try {

HttpURLConnection httpConnection = (HttpURLConnection) connection;

httpConnection.setRequestMethod("GET");

httpConnection.connect();

if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {

i = httpConnection.getInputStream();

}

} catch (Exception ex) {

ex.printStackTrace();

}

bis = new BufferedInputStream(i,1024 * 8);

out = new ByteArrayOutputStream();

int len=0;

byte[] buffer = new byte[1024];

while((len = bis.read(buffer)) != -1){

out.write(buffer, 0, len);

}

byte[] data = out.toByteArray();

out.close();

bis.close();

BitmapFactory.Options options = new BitmapFactory.Options();

options.inJustDecodeBounds=true;

Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);

return bitmap;

} catch (Exception e) {

return null;

}

}'

I Don't know Why? Please Help Me. Thanks !

I Know : Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);

bitmap = null ( 4.2.2, 4.3)

bitmap not null ( 2.3.3 )

网友答案:

It seems that you are using network on the UI thread. You need to access network in other thread. Have a look at AsyncTask

网友答案:

try this:

Remeber to add these permissions:

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

class BitmapGetter extends AsyncTask<String, Integer, Drawable> {
    @Override
    protected Drawable doInBackground(String... params) {
        Drawable bmpRet = null;
        try {
            BufferedInputStream in = new BufferedInputStream(new URL(params[0]).openStream());
            bmpRet = new BitmapDrawable(getResources(), BitmapFactory.decodeStream(in));
            in.close();
        } catch (Exception e) {return null;}
        return bmpRet;
    }

    public void onPostExecute(Drawable result) {
        try {
            (findViewById(R.id.imageView1)).setBackgroundDrawable(result);
        } catch (Exception ex) {}
    }
}

and execute it from Main class:

    new BitmapGetter().execute("http://i.stack.imgur.com/MuhXg.jpg");
分享给朋友:
您可能感兴趣的文章:
随机阅读: