Tuesday 30 September 2014

Displaying images form list of urls in android.

Now I am going to discuss about how to display images from list of url in android.

Let's follow some code standardization. Code Standardization is where no constants should be declared inside the class file. It should be moved by creating Constants.java. and for xml you can use strings.

Flow of the application is When you click from Listview, it displays images where I am using viewpager to swipe image from left to right and vice versa.

Getting a list of constants urls
Constants.java:

public final class Constants {
public static final String[] aakansha={
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-001.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-002.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-003.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-004.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-005.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-006.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-007.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-008.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-009.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-010.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-011.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-012.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-013.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-014.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-016.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-017.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-018.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-019.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-021.jpg",
           "http://tamil.cinesnacks.net/photos/actress/Aakansha/aakansha-marudhavelu-movie-actress-022.jpg",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png"
         
   };

public static final String[] mStrings1={
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image0.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image1.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image2.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image3.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image4.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image5.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image6.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image7.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image8.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image9.png",
           "http://androidexample.com/media/webservice/LazyListView_images/image10.png"
         
   };
}

 Create ListActivity.java

import com.example.constants.Constants;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ListActivity extends Activity {
private ListView list;
HelpAdapter adapter;
   private Static final String KEY="key";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] listItems = getResources().getStringArray(R.array.help_items);

   list = (ListView) findViewById(R.id.listview);
   adapter = new HelpAdapter(this,listItems);
   list.setAdapter(adapter);
   list.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
if(position==0){
Intent intent=new Intent(ListActivity.this,ViewPagerSwipe.class);
intent.putExtra(KEY, Constants.aakansha); //pass the key and value.
startActivity(intent);
}
if(position==1){
Intent intent=new Intent(ListActivity.this,ViewPagerSwipe.class);
intent.putExtra(KEY, Constants.mStrings1);
startActivity(intent);
}
}
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}

}

main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".ListActivity" >

     <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/listview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="6dp" >
        </ListView>
    </LinearLayout>

</RelativeLayout>


I created a custom Adapter as for further development, I may place image and text too..Now just a text been used in HelpAdapter

HelpAdapter.java:

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class HelpAdapter extends BaseAdapter {
    // Declare Variables
    private Context context;
    private String[] rank;
    private LayoutInflater inflater;
    public HelpAdapter(Context context, String[] rank) {
        this.context = context;
        this.rank = rank;
    }
    @Override
    public int getCount() {
        return rank.length;
    }
    @Override
    public Object getItem(int position) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView helpText;
        ImageView imgflag;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.activity_help_row, parent, false);
        // Locate the TextViews in activity_help_row.xml
        helpText = (TextView) itemView.findViewById(R.id.helptext);
        // Locate the ImageView in activity_help_row.xml
        // Capture position and set to the TextViews
        helpText.setText(rank[position]);
        // Capture position and set to the ImageView
        return itemView;
    }
}
activity_help_row.xml:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <RelativeLayout
        android:id="@+id/helpTextLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:orientation="vertical"
        android:visibility="visible" >

        <TextView
            android:id="@+id/helptext"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp" />

    </RelativeLayout>

</LinearLayout>

and in strings.xml: for array items, declare it. as I used in ListActivity to get collection of items in array. Always don't declare any constants in java file.Best practice is use in strings.

  final String[] listItems = getResources().getStringArray(R.array.help_items);


<array name="help_items">
        
        <item>A</item>
        <item>B</item>
    </array>

ViewPagerSwipe.java :

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.widget.Toast;

public class ViewPagerSwipe extends Activity {
ViewPagerAdapter viewpageradapter;
ViewPager viewpager;
private int currentPage;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.viewpage);
 Bundle extras = getIntent().getExtras();
 if(extras !=null) {
   String[] value = extras.getStringArray(ListActivity.KEY); // since it has been declared public.
 ViewPager viewpager=(ViewPager)findViewById(R.id.myfivepanelpager);
 viewpageradapter=new ViewPagerAdapter(this,value);
 viewpager.setCurrentItem(0);
 viewpager.setAdapter(viewpageradapter);
 currentPage=viewpageradapter.getCount();
 viewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
 
}
}

}

viewpage.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <android.support.v4.view.ViewPager
        android:id="@+id/myfivepanelpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

ViewPagerAdapter.java:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import android.net.Uri;
import com.example.utils.ImageLoader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;

public class ViewPagerAdapter extends PagerAdapter {
Activity activity;
String imgArray[];
public ImageLoader imageLoader; 

public ViewPagerAdapter(Activity act, String[] imgArra) {
imgArray=imgArra;
activity=act;
   imageLoader=new ImageLoader(activity.getApplicationContext());

// TODO Auto-generated constructor stub
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return imgArray.length;
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0 == ((View) arg1);
}
public Object instantiateItem(View collection, int position) {
View view=null;
LayoutInflater layoutinflater=(LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutinflater.inflate(R.layout.adapter, null);
int count=getCount();
final ImageView image=(ImageView)view.findViewById(R.id.imageView1);
image.setScaleType(ScaleType.FIT_XY);
imageLoader.DisplayImage(imgArray[position], image);
// image.setBackgroundResource(imgArray[position]);
 ((ViewPager) collection).addView(view, 0);
return view;
 
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
 ((ViewPager) arg0).removeView((View) arg2);
}


@Override
public Parcelable saveState() {
 return null;
}

}

adapter.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="fill_parent"
        android:layout_height="match_parent"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

As I used image loader. Add the jar file of image loader or use the package

FileCache.java:

import java.io.File;
import android.content.Context;
public class FileCache {
     
    private File cacheDir;
     
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TTImages_cache");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
     
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        //String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
         
    }
     
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }
}

ImageLoader.java:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
public class ImageLoader {
     
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 
     
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
     
    final int stub_id=R.drawable.ic_launcher;
    public void DisplayImage(String url, ImageView imageView)
    {
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(stub_id);
        }
    }
         
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
     
    private Bitmap getBitmap(String url) 
    {
        File f=fileCache.getFile(url);
         
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
         
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Throwable ex){
           ex.printStackTrace();
           if(ex instanceof OutOfMemoryError)
               memoryCache.clear();
           return null;
        }
    }
    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
             
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=200;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
             
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
     
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u; 
            imageView=i;
        }
    }
     
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
         
        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
     
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
     
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }
    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
}

MemoryCache.java:

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.graphics.Bitmap;
import android.util.Log;
public class MemoryCache {
    private static final String TAG = "MemoryCache";
    private Map<String, Bitmap> cache=Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(10,1.5f,true));//Last argument true for LRU ordering
    private long size=0;//current allocated size
    private long limit=1000000;//max memory in bytes
    public MemoryCache(){
        //use 25% of available heap size
        setLimit(Runtime.getRuntime().maxMemory()/4);
    }
     
    public void setLimit(long new_limit){
        limit=new_limit;
        Log.i(TAG, "MemoryCache will use up to "+limit/1024./1024.+"MB");
    }
    public Bitmap get(String id){
        try{
            if(!cache.containsKey(id))
                return null;
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            return cache.get(id);
        }catch(NullPointerException ex){
            ex.printStackTrace();
            return null;
        }
    }
    public void put(String id, Bitmap bitmap){
        try{
            if(cache.containsKey(id))
                size-=getSizeInBytes(cache.get(id));
            cache.put(id, bitmap);
            size+=getSizeInBytes(bitmap);
            checkSize();
        }catch(Throwable th){
            th.printStackTrace();
        }
    }
     
    private void checkSize() {
        Log.i(TAG, "cache size="+size+" length="+cache.size());
        if(size>limit){
            Iterator<Entry<String, Bitmap>> iter=cache.entrySet().iterator();//least recently accessed item will be the first one iterated  
            while(iter.hasNext()){
                Entry<String, Bitmap> entry=iter.next();
                size-=getSizeInBytes(entry.getValue());
                iter.remove();
                if(size<=limit)
                    break;
            }
            Log.i(TAG, "Clean cache. New size "+cache.size());
        }
    }
    public void clear() {
        try{
            //NullPointerException sometimes happen here http://code.google.com/p/osmdroid/issues/detail?id=78 
            cache.clear();
            size=0;
        }catch(NullPointerException ex){
            ex.printStackTrace();
        }
    }
    long getSizeInBytes(Bitmap bitmap) {
        if(bitmap==null)
            return 0;
        return bitmap.getRowBytes() * bitmap.getHeight();
    }
}

Utils.java:

import java.io.InputStream;
import java.io.OutputStream;
public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}

If you want to save or share an image.Create a button in adapter.xml or you can also use it in menu based on your requiremnt. I just show it in ViewPagerAdapter.

 public Object instantiateItem(View collection, int position) {
    LayoutInflater layoutinflater=(LayoutInflater)collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutinflater.inflate(R.layout.adapter, null);
Button save=(Button)view.findViewById(R.id.savebutton);
Button share=(Button)view.findViewById(R.id.sharebutton);
save.setText("Save"+count);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
 BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
       Bitmap bitmap = bitmapDrawable.getBitmap();
 
       // Save this bitmap to a file.
       File cache = activity.getExternalCacheDir();
       File sharefile = new File(cache, "save.png"); //give your name and save it.
       try {
           FileOutputStream out = new FileOutputStream(sharefile);
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
           out.flush();
           out.close();
       } catch (IOException e) {
         
       }
 
       // Now send it out to share
       Intent share = new Intent(android.content.Intent.ACTION_SEND);
       share.setType("image/*");
       share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
       try {
           activity.startActivity(Intent.createChooser(share, "Share photo"));
       } catch (Exception e) {
           
       }
}
});
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
image.setDrawingCacheEnabled(true);
               Bitmap bitmap = image.getDrawingCache();
               
               String root = Environment.getExternalStorageDirectory().toString();
               File newDir = new File(root + "/Nokia");    
               newDir.mkdirs();
               Random gen = new Random();
               int n = 10000;
               n = gen.nextInt(n);
               String fotoname = "Photo-"+ n +".jpg";
               File file = new File (newDir, fotoname);
               if (file.exists ()) file.delete (); 
                try {
                      FileOutputStream out = new FileOutputStream(file);
                      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                      out.flush();
                      out.close();
                      Toast.makeText(activity, "Saved to your folder"+fotoname, Toast.LENGTH_SHORT ).show();

               } catch (Exception e) {
                
               }
                       
            }
}) ;
             //others all are same.
image.setScaleType(ScaleType.FIT_XY);
imageLoader.DisplayImage(imgArray[position], image);
// image.setBackgroundResource(imgArray[position]);
 ((ViewPager) collection).addView(view, 0);
return view;
 
}

Happy Coding.. :)





No comments:

Post a Comment