Aim: To download image from web and display it in android Application.
Procedure: Here we are going to use URL of image to be downloaded. After downloading that Image we need to display it in application so we used Imageview, Bitmap, Bitmapfactory to our application.
Permission: For this application we need to take Internet permission from android.
<uses-permission android:name="android.permission.INTERNET" />
Code:
public class ImageCacheActivity extends Activity {
ImageView image;
Button download;
Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image=(ImageView) findViewById(R.id.image);
download=(Button) findViewById(R.id.btnset);
download.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://www.google.co.uk/logos/holiday09_2.gif");
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Output:
Before running application check your Network setting that means Proxy,Port etc.
Procedure: Here we are going to use URL of image to be downloaded. After downloading that Image we need to display it in application so we used Imageview, Bitmap, Bitmapfactory to our application.
Permission: For this application we need to take Internet permission from android.
<uses-permission android:name="android.permission.INTERNET" />
Code:
public class ImageCacheActivity extends Activity {
ImageView image;
Button download;
Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image=(ImageView) findViewById(R.id.image);
download=(Button) findViewById(R.id.btnset);
download.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = new URL("http://www.google.co.uk/logos/holiday09_2.gif");
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
image.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Output:
Before running application check your Network setting that means Proxy,Port etc.

No comments:
Post a Comment