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
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:
Call it as:
Hope this helps.