简体   繁体   中英

Android BinaryFactory.decodeStream always return null

I am trying to download image and decode it to bitmap using BitmapFactory, but decodeStream always return null. I've googled many similar questions, tried many examples, but didn't find solution.

Here is my code:

    public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void downloadButton(View v)
    {
        String imageUrl = "http://www.picgifs.com/bird-graphics/bird-graphics/elf-owl/bird-graphics-elf-owl-527150.bmp";
        new Thread(new ImageDownloader(imageUrl)).start();
    }

    public void showImageButton(View v)
    {
        Bitmap image = ImageHandler.getImage();
        if (image == null)
            Log.e("Error", "No image available");
        else {
            ImageView imageView = (ImageView)findViewById(R.id.ImageView);
            imageView.setImageBitmap(image);
        }
    }
}

class ImageHandler
{
    static protected List<Bitmap> imagesList;
    static public void addImage(Bitmap image)
    {
        imagesList.add(image);
    }
    static public Bitmap getImage()
    {
        if (!imagesList.isEmpty())
            return imagesList.get(0);
        else
            return null;
    }
}

class ImageDownloader implements Runnable
{
    public Bitmap bmpImage;
    private String urlString;
    public ImageDownloader(String urlString)
    {
        this.urlString = urlString;
    }
    public void run()
    {
        try
        {
            AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
            HttpGet getRequest = new HttpGet(urlString);
            HttpResponse response = client.execute(getRequest);
            HttpEntity entity = response.getEntity();
            InputStream inputStream = null;
            inputStream = (new BufferedHttpEntity(entity)).getContent();
            bmpImage = BitmapFactory.decodeStream(inputStream);
            //bmpImage = BitmapFactory.decodeStream(new URL(urlString).openConnection().getInputStream());
        }
        catch (Exception e)
        {
            Log.e("ImageDownloadError", e.toString());
            return;
        }
        if (bmpImage != null)
        {
            ImageHandler.addImage(bmpImage);
            Log.i("Info", "Image download successfully");
        }
        else
            Log.e("Error", "Bitmap is null");
    }
}

ps showImageButton throws IllegalStateException , but I was already sick of it.

I think the problem is that once you've used an InputStream from a HttpUrlConnection, you can't rewind and use the same InputStream again. Therefore you have to create a new InputStream for the actual sampling of the image. Otherwise we have to abort the http request.

Only once we can use inputstream for httprequest, if you are trying to download another image,then it will throw an error as "InputStream already created" like this. so we need to abort the httprequest once downloaded using httpRequest.abort();

Use this:

HttpGet httpRequest = new HttpGet(URI.create(path) );
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmp = BitmapFactory.decodeStream(bufHttpEntity.getContent());
httpRequest.abort();

as per my view two Reasons are there

  1. class ImageHandler is not able to get the image
  2. android is giving problem to take gif image from source.

I am uploading a working code hope this will solve Your Problem.

MainActivity

 public class MainActivity extends Activity {

    private ProgressDialog progressDialog;
    private ImageView imageView;
    private String url = "http://www.9ori.com/store/media/images/8ab579a656.jpg";
    private Bitmap bitmap = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        Button start = (Button) findViewById(R.id.button1);
        start.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                progressDialog = ProgressDialog.show(MainActivity.this,
                        "", "Loading..");
                new Thread() {
                    public void run() {
                        bitmap = downloadBitmap(url);
                        messageHandler.sendEmptyMessage(0);
                    }
                }.start();

            }
        });
    }

    private Handler messageHandler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imageView.setImageBitmap(bitmap);
            progressDialog.dismiss();
        }
    };

    private Bitmap downloadBitmap(String url) {
        // Initialize the default HTTP client object
        final DefaultHttpClient client = new DefaultHttpClient();

        //forming a HttoGet request
        final HttpGet getRequest = new HttpGet(url);
        try {

            HttpResponse response = client.execute(getRequest);

            //check 200 OK for success
            final int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                Log.w("ImageDownloader", "Error " + statusCode +
                        " while retrieving bitmap from " + url);
                return null;
            }

            final HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = null;
                try {
                    // getting contents from the stream
                    is = entity.getContent();

                    // decoding stream data back into image Bitmap
                    final Bitmap bitmap = BitmapFactory.decodeStream(is);

                    return bitmap;
                } finally {
                    if (is != null) {
                        is.close();
                    }
                    entity.consumeContent();
                }
            }
        } catch (Exception e) {
            getRequest.abort();
            Log.e(getString(R.string.app_name), "Error "+ e.toString());
        }

        return null;
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dp"
        android:text="Download Image" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerInside"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

and also don't forget to give INTERNET Permission in Manifest.xml file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM