Android – Download and display an image from an URL

În aplicaţiile Android este frecventă utilizarea imaginilor. Pentru a afişa o imagine se utilizează controlul ImageView. De asemenea de foarte multe ori este necesară preluarea imaginilor de pe un server web, iar acest tip de implementare va fi abordată în tutorialul prezent.

Planul de atac este foarte simplu: există la un anumit URL o imagine care va fi afişata într-un ImageView, iar pentru a fi puţin mai interesantă mini-aplicaţia se va salva şi local imaginea preluată de la adresa web specificată. Se verifică existenţa unei conexiuni la internet şi în cazul în care nu există se afişează un alert.

Design:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:padding="10dip"
 android:background="@drawable/white">
 <ImageView android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:id = "@+id/imgDisplay">
 </ImageView>
 <Button android:layout_width="100dip"
 android:layout_height="50dip"
 android:text="Display image"
 android:layout_alignParentBottom="true"
 android:layout_centerHorizontal="true"
 android:background="@drawable/style_button"
 android:onClick="btnDisplayImage_onClick">
 </Button>
</RelativeLayout>

style_button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_pressed="false"
 android:drawable="@drawable/background_button_yellow" />
 <item android:state_pressed="true"
 android:drawable="@drawable/background_button_blue" />
</selector>


Implementare:

DisplayImageActivity .java

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class DisplayImageActivity extends Activity
{

 private static String url = "https://magdabadita.files.wordpress.com/2011/11/open_msg.png";
 private ImageView imgDisplay;

 @Override
 public void onCreate(Bundle savedInstanceState)
 {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);

 imgDisplay = (ImageView)findViewById(R.id.imgDisplay);
 }

public void btnDisplayImage_onClick(View v)
 {
 if(AlertDialogs.checkNetworkStatus(this))
 {
 setImageVodafoneSplashScreen(this, imgDisplay);
 }
 else
 {
 AlertDialogs.createAlertDialogNoInternetConn(this);
 }
 }

public void setImageVodafoneSplashScreen(Context c, ImageView imgVodafone)
 {
 try
 {
 Drawable image = imageOperations(url);
 imgVodafone.setImageDrawable(image);
 URL urlPhoto = new URL(url);
 InputStream input = urlPhoto.openStream();
 FileOutputStream fos;
 try
 {
 fos = c.openFileOutput("image_from_web.png", Context.MODE_PRIVATE);
 byte[] buffer = new byte[1024*2];
 int bytesRead = 0;
 while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
 {
 fos.write(buffer, 0, buffer.length);
 }
 fos.close();
 String path = c.getFilesDir().toString();
 String fileName = "label_vodafone.png";
 if (fileName != null && !fileName.equals(""))
 {
 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 4;
 Bitmap bMap = BitmapFactory.decodeFile(path + "/" + fileName, options);
 if (bMap != null)
 {
 imgVodafone.setImageBitmap(bMap);
 }
 }
 }
 catch (FileNotFoundException e)
 {
 e.printStackTrace();
 }
 catch (IOException e)
 {
 e.printStackTrace();
 }
 catch(Exception e)
 {
 e.printStackTrace();
 }
 }
 catch(Exception ex)
 {
 ex.printStackTrace();
 }
 }

 public Drawable imageOperations(String url)
 {
 try
 {
 InputStream is = (InputStream) this.fetch(url);
 BufferedInputStream bis = new BufferedInputStream(is);
 Drawable d = Drawable.createFromStream(bis, "src");
 bis.close();
 is.close();
 return d;
 }
 catch (MalformedURLException e)
 {
 return null;
 }
 catch (IOException e)
 {
 return null;
 }
 }

 public Object fetch(String address) throws MalformedURLException, IOException
 {
 URL url = new URL(address);
 Object content = url.getContent();
 return content;
 }
}


AlertsDialog.java

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;

public class AlertDialogs
{
 public static boolean checked ;

 public static void createAlertDialogNoInternetConn(Context ctx)
 {
 AlertDialog alertDialog = new AlertDialog.Builder(ctx).create();
 alertDialog.setTitle("Connection error");
 alertDialog.setMessage("Awww, shoot. Your phone is having trouble connecting to our servers right now. Try again shortly!");
 alertDialog.setButton("OK", new DialogInterface.OnClickListener()
 {
 public void onClick(DialogInterface dialog, int which){}
 });
 alertDialog.setIcon(R.drawable.ic_app);
 alertDialog.show();
 }

 public static boolean checkNetworkStatus(Context ctx)
 {
 ConnectivityManager con=(ConnectivityManager)ctx.getSystemService(Activity.CONNECTIVITY_SERVICE);
 boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
 boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
 if(wifi || internet)
 {
 return true;
 }
 else
 {
 return false;
 }
 }
}

Permisiuni:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Enjoy!!!

Advertisements
Android – Download and display an image from an URL

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s