android - (HttpURLConnection) downloading image from internet

1.9k views Asked by At

I want to create a simple android app that retrieves an image from the internet The Activity code looks like this :

import java.io.IOException;
import java.io.InputStream;

import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;

public class BitmapDemo extends ActionBarActivity {
    //bikin objek image view nya
    ImageView imageview;

    private Bitmap downloadImage(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        Koneksi koneksi = new Koneksi();  //class untuk koneksi nya

        try{
            in = koneksi.OpenHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException ex){
            Toast.makeText(this, ex.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            ex.printStackTrace();
        }

        return bitmap;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap_demo);

        //download image nya
        //Bitmap bitmap = downloadImage("http://10.0.3.2/mp/tux2.jpeg");  //localhost
        Bitmap bitmap = downloadImage("http://infinitejest.wallacewiki.com/david-foster-wallace/images/a/ab/Nasa_Emblem.jpg");  //localhost
        //Bitmap bitmap = downloadImage("nama saya luki");  //localhost
        imageview = (ImageView)findViewById(R.id.imageview);
        imageview.setImageBitmap(bitmap);
    }

And for the connection, i created a class called Koneksi.java (called in the activity on line 22

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

//import org.apache.http.HttpConnection;

public class Koneksi {
    public InputStream OpenHttpConnection(String urlString) throws IOException{
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        final URLConnection conn = url.openConnection();

        if(!(conn instanceof HttpURLConnection)){
            throw new IOException("String yang dimasukkan bukan alamat web");
        }

                try{
                    HttpURLConnection httpCon = (HttpURLConnection) conn;
                    httpCon.setAllowUserInteraction(false);
                    httpCon.setInstanceFollowRedirects(true);
                    httpCon.setRequestMethod("GET");
                    httpCon.connect();

                    //apakah respon berhasil
                    response = httpCon.getResponseCode();
                    if(response == HttpURLConnection.HTTP_OK){  //sama dengan 200 ga ya
                        in = httpCon.getInputStream();
                    }
                }

                catch(Exception ex){
                    //ex.printStackTrace();
                    throw new IOException("koneksi error");
                }

        return in; 
    }
}

When i execute the app, the catch on Koneksi.java throws, saying "koneksi error". Am i missing something?

Note : i have already add "android.permission.ACCESS_NETWORK_STATE" and also "android.permission.INTERNET" in the manifest

3

There are 3 answers

0
MysticMagicϡ On BEST ANSWER

You have added the permissions. Fine. But you need to create AsyncTask for performing this.

You are trying to access Network on main thread.

Change your Koneksi class to an AsyncTask:

private class Koneksi extends AsyncTask<String, Integer, String>  {

    protected String doInBackground(String... params) {
        //your code for downloading image    
    }

    protected void onPostExecute(String result) {
        //handle result
    }
}

Call it as:

new Koneksi().execute(params);  //params is a String array of input if any.

Hope this helps.

0
Alu On

In Android you can not open a network connection from the main-thread. The user interface runs on the main-thread, so every connection will interrupt the interface and you can't do anything while the download is performed.

You have to build a helper class, which connects in the background and does a callback when the download finished.

See here: Perform Network Operations on a Separate Thread

0
culebrins On

A fast and easy way for you:

    public class MyRunnable implements Runnable{

    private String url;
    public MyRunnable (String _url){
        url=_url;
    }

    @Override
    public void run() {
        final Bitmap bitmap;
        InputStream in = null;
        Koneksi koneksi = new Koneksi();  //class untuk koneksi nya

        try{
            in = koneksi.OpenHttpConnection(url);
            bitmap = BitmapFactory.decodeStream(in);
            in.close();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
        BitmapDemo.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                imageview = (ImageView) findViewById(R.id.imageview);
                imageview.setImageBitmap(bitmap);
            }
        });
    }
}

and in your code:

private Bitmap downloadImage(String url){
    Thread t = new Thread(new MyRunnable(url));
    t.start();
}