Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.downloadingimageandpuingrid;
- import android.support.v7.app.ActionBarActivity;
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.widget.ImageView;
- public class MainActivity extends ActionBarActivity {
- public String url;
- public Byte [] imageBytes;
- public ImageView imageView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.gallery_item);
- imageView = (ImageView) findViewById(R.layout.gallery_item);
- url = "http://animalia-life.com/odin/Cat/cat5.html";
- new FetchItemsTask().execute();
- }
- private class FetchItemsTask extends AsyncTask<Void,Void, byte[] > {
- @Override
- protected byte[] doInBackground(Void... params) {
- return new UrlDownload().getUrlBytes(url);
- }
- @Override
- protected void onPostExecute(byte[] imageBytes) {
- final Bitmap bitmap = BitmapFactory
- .decodeByteArray(imageBytes, 0, imageBytes.length);
- imageView.setImageBitmap(bitmap);
- }
- }
- }
- package com.example.downloadingimageandpuingrid;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import android.util.Log;
- public class UrlDownload {
- byte[] getUrlBytes(String urlSpec)
- {
- try{
- return download(urlSpec);
- } catch(Exception e){
- //e.printStackTrace();
- Log.e("UrlDownload", "error downloading");
- byte[] empety = {};
- return empety;
- }
- }
- public byte[] download (String urlSpec) throws IOException
- {
- URL url = new URL(urlSpec);
- HttpURLConnection connection = (HttpURLConnection)url.openConnection();
- try {
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- InputStream in = connection.getInputStream();
- if (connection.getResponseCode() != HttpURLConnection.HTTP_OK)
- {
- return null;
- }
- int bytesRead = 0;
- byte[] buffer = new byte[1024];
- while ((bytesRead = in.read(buffer)) > 0)
- {
- out.write(buffer, 0, bytesRead);
- }
- out.close();
- return out.toByteArray();
- }
- finally {
- connection.disconnect();
- }
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <ImageView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gallery_item_imageView"
- android:layout_width="match_parent"
- android:layout_height="120dp"
- android:layout_gravity="center"
- android:scaleType="centerCrop" >
- </ImageView>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement