Wednesday 23 April 2014

GridView loading photos from SD Card folder

Add a <GridView> in layout.


<LinearLayout 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:orientation="vertical">

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"/>

</LinearLayout>

Main code:


package com.example.androidgridview;

import java.io.File;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class Addnewwallpaper extends Activity
{

 ArrayList<String> itemList = new ArrayList<String>();


 ImageAdapter myImageAdapter;

 Button addimg ;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
  setContentView(R.layout.addnewwallpaper);

  addimg =  (Button) findViewById(R.id.addimg);
  addimg.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Intent i = new Intent(Addnewwallpaper.this, ChooseFoldertoaddInPhotovoltActivity.class);
    startActivity(i);

   }
  });
  final GridView gridview = (GridView) findViewById(R.id.gridview);
  myImageAdapter = new ImageAdapter(this);
  gridview.setAdapter(myImageAdapter);

  String ExternalStorageDirectoryPath = Environment
    .getExternalStorageDirectory()
    .getAbsolutePath();

  String targetPath = ExternalStorageDirectoryPath + "/Livewallaper/";

  // Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
  File targetDirector = new File(targetPath);

  File[] files = targetDirector.listFiles();
  for (File file : files){
   myImageAdapter.add(file.getAbsolutePath());
  } 


  gridview.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> arg0, View arg1, int position,
     long arg3) {
    // TODO Auto-generated method stub

    //Toast.makeText(getApplicationContext(), ""+itemList.get(position), Toast.LENGTH_LONG).show();
    File filederectory = new File(itemList.get(position).toString());
    DeleteRecursive(filederectory);

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
      Uri.parse("file://"
        + Environment.getExternalStorageDirectory())));

    itemList.clear();
    itemList = new ArrayList<String>();

    String ExternalStorageDirectoryPath = Environment
      .getExternalStorageDirectory()
      .getAbsolutePath();

    String targetPath = ExternalStorageDirectoryPath + "/Livewallaper/";

    // Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
    File targetDirector = new File(targetPath);

    File[] files = targetDirector.listFiles();
    for (File file : files){
     myImageAdapter.add(file.getAbsolutePath());
    } 
    myImageAdapter.notifyDataSetChanged();
    gridview.invalidateViews();
    gridview.setAdapter(new ImageAdapter(Addnewwallpaper.this));
    myImageAdapter.notifyDataSetChanged();
   }
  });
 }
 void DeleteRecursive(File fileOrDirectory) {

  if (fileOrDirectory.isDirectory())
   for (File child : fileOrDirectory.listFiles())
    DeleteRecursive(child);

  fileOrDirectory.delete();

 }

 public class ImageAdapter extends BaseAdapter {

  private Context mContext;


  public ImageAdapter(Context c) {
   mContext = c; 
  }

  void add(String path){
   itemList.add(path); 
  }

  @Override
  public int getCount() {
   return itemList.size();
  }

  @Override
  public Object getItem(int arg0) {
   // TODO Auto-generated method stub
   return null;
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   ImageView imageView;
   if (convertView == null) {  // if it's not recycled, initialize some attributes
    imageView = new ImageView(mContext);
    imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(8, 8, 8, 8);
   } else {
    imageView = (ImageView) convertView;
   }

   Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);

   imageView.setImageBitmap(bm);
   return imageView;
  }

  public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

   Bitmap bm = null;
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, options);

   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   bm = BitmapFactory.decodeFile(path, options); 

   return bm;   
  }

  public int calculateInSampleSize(

    BitmapFactory.Options options, int reqWidth, int reqHeight) {
   // Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;

   if (height > reqHeight || width > reqWidth) {
    if (width > height) {
     inSampleSize = Math.round((float)height / (float)reqHeight);    
    } else {
     inSampleSize = Math.round((float)width / (float)reqWidth);    
    }   
   }

   return inSampleSize;    
  }

 }
}

Monday 21 April 2014

Get file list form sdcard folder in android

 String root_sd2 = Environment.getExternalStorageDirectory().toString();
            File file1 = new File( root_sd2 + "/Fodler name" ) ;      
            File list1[] = file1.listFiles();
            totalImages = list1.length;


OR
int totalImages = 0;
String root_sd = Environment.getExternalStorageDirectory().toString();
                File imglista = new File( root_sd + "/Folder NAme" ) ;      
                File imginfolder[] = imglista.listFiles();
                bitmap = BitmapFactory.decodeFile(imginfolder[totalImages ].getAbsolutePath());

How to transfer image or copy image from assets to SD card in android

Define 

String secureImagesvoltpath=Environment.getExternalStorageDirectory() + "/Livewallaper";

In On Create
createSecuredirectoryifNotExist("kiritbhayani");
       
        CopyAssets();


Methods

public void  createSecuredirectoryifNotExist(String encrypteddirectoryName) {
       
        File dir = new File(secureImagesvoltpath);
          if(dir.exists() && dir.isDirectory()) {
              System.out.println("Directory exist");
          }
          else{
             
              try{
                  if(dir.mkdirs()) {
                     System.out.println("Directory created");
                  } else {
                     System.out.println("Directory is not created");
                  }
                }catch(Exception e){
                  e.printStackTrace();
                }
           
         }
    }
private void CopyAssets() {
            AssetManager assetManager = getAssets();
            String[] files = null;
            try {
                files = assetManager.list("AssetsFoldername");
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }
   
            for(String filename : files) {
                System.out.println("File name => "+filename);
                InputStream in = null;
                OutputStream out = null;
                try {
                  in = assetManager.open("Files/"+filename);   // if files resides inside the "Files" directory itself
                  out = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+"/Livewallaper" +"/" + filename);
                  copyFile(in, out);
                  in.close();
                  in = null;
                  out.flush();
                  out.close();
                  out = null;
                } catch(Exception e) {
                    Log.e("tag", e.getMessage());
                }
            }
        }
        private void copyFile(InputStream in, OutputStream out) throws IOException {
            byte[] buffer = new byte[1024];
            int read;
            while((read = in.read(buffer)) != -1){
              out.write(buffer, 0, read);
            }
        }

How to Programmatically Zip and Unzip File in Android

How to Zip files.

1) Persmissions in Manifest File.

Crete a sample android activity and add the following permission to application Mainfest.xml file. These persmissions are required to store data to your device storage.

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
2) In Java File
 
 
public void zip(String[] _files, String zipFileName) {
        try {
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFileName);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
                    dest));
            byte data[] = new byte[BUFFER];
 
            for (int i = 0; i < _files.length; i++) {
                Log.v("Compress", "Adding: " + _files[i]);
                FileInputStream fi = new FileInputStream(_files[i]);
                origin = new BufferedInputStream(fi, BUFFER);
 
                ZipEntry entry = new ZipEntry(_files[i].substring(_files[i].lastIndexOf("/") + 1));
                out.putNextEntry(entry);
                int count;
 
                while ((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
                origin.close();
            }
 
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
~You can use this in your activity~
 
// declare an array for storing the files i.e the path
// of your source files
String[] s = new String[2];
 
// Type the path of the files in here
s[0] = inputPath + "/image.jpg";
s[1] = inputPath + "/textfile.txt"; // /sdcard/ZipDemo/textfile.txt
 
// first parameter is d files second parameter is zip file name
ZipManager zipManager = new ZipManager();
 
// calling the zip function
zipManager.zip(s, inputPath + inputFile);
 
 
 

How to UnZip files.

1) Persmissions in Manifest File.

Crete a sample android activity and add the following permission to application Mainfest.xml file. These persmissions are required to store data to your device storage.

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 
2) In Java File
 
public void unzip(String _zipFile, String _targetLocation) {
 
        //create target location folder if not exist
        dirChecker(_targetLocatioan);
 
        try {
            FileInputStream fin = new FileInputStream(_zipFile);
            ZipInputStream zin = new ZipInputStream(fin);
            ZipEntry ze = null;
            while ((ze = zin.getNextEntry()) != null) {
 
                //create dir if required while unzipping
                if (ze.isDirectory()) {
                    dirChecker(ze.getName());
                } else {
                    FileOutputStream fout = new FileOutputStream(_targetLocation + ze.getName());
                    for (int c = zin.read(); c != -1; c = zin.read()) {
                        fout.write(c);
                    }
 
                    zin.closeEntry();
                    fout.close();
                }
 
            }
            zin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
}
 
 
~You can use this Method in your activity~
 
ZipManager zipManager = new ZipManager();
zipManager.unzip(inputPath + inputFile, outputPath);
 
 
 
 
 
 
 
 
 
 
 


Sunday 20 April 2014

Delete Folder & copy and movig file in Android

How to delete folder..?

public static void deleteFiles(String path) {

    File file = new File(path);

    if (file.exists()) {
        String deleteCmd = "rm -r " + path;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(deleteCmd);
        } catch (IOException e) { }
    }
}
 
 
 OR 
 
void DeleteRecursive(File fileOrDirectory) {

   if (fileOrDirectory.isDirectory())
      for (File child : fileOrDirectory.listFiles())
          DeleteRecursive(child);

      fileOrDirectory.delete();

      } 

 copy and movig file 

Two way 

1)

 
private void copyFilenew(String inputPath, String inputFile, String outputPath) {

     InputStream in = null;
     OutputStream out = null;
     try {

         //create output directory if it doesn't exist
         File dir = new File (outputPath); 
         if (!dir.exists())
         {
             dir.mkdirs();
         }

         in = new FileInputStream(inputPath + inputFile);        
         out = new FileOutputStream(outputPath + inputFile);

         byte[] buffer = new byte[1024];
         int read;
         while ((read = in.read(buffer)) != -1) {
             out.write(buffer, 0, read);
         }
         in.close();
         in = null;

             // write the output file (You have now copied the file)
             out.flush();
         out.close();
         out = null;        

     }  catch (FileNotFoundException fnfe1) {
         Log.e("tag", fnfe1.getMessage());
     }
             catch (Exception e) {
         Log.e("tag", e.getMessage());
     }

 }
 
 
OR
 
 
public static boolean copyFile(String from, String to) {
  try {
   File sd = Environment.getExternalStorageDirectory();
   if (sd.canWrite()) {
    int end = from.toString().lastIndexOf("/");
    String str1 = from.toString().substring(0, end);
    String str2 = from.toString().substring(end+1, from.length());
    File source = new File(str1, str2);
    File destination= new File(to, str2);
    if (source.exists()) {
     FileChannel src = new FileInputStream(source).getChannel();
     FileChannel dst = new FileOutputStream(destination).getChannel();
     dst.transferFrom(src, 0, src.size());
     src.close();
     dst.close();
    }
   }
   return true;
  } catch (Exception e) {
   return false;
  }
 }  

2)
 public static void copyDirectoryOneLocationToAnotherLocation(File sourceLocation, File targetLocation)
   throws IOException {

  if (sourceLocation.isDirectory()) {
   if (!targetLocation.exists()) {
    targetLocation.mkdir();
   }

   String[] children = sourceLocation.list();
   for (int i = 0; i < sourceLocation.listFiles().length; i++) {

    copyDirectoryOneLocationToAnotherLocation(new File(sourceLocation, children[i]),
      new File(targetLocation, children[i]));
   }
  } else {

   InputStream in = new FileInputStream(sourceLocation);

   OutputStream out = new FileOutputStream(targetLocation);

   // Copy the bits from instream to outstream
   byte[] buf = new byte[1024];
   int len;
   while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
   }
   in.close();
   out.close();
  }

 }
 
 
 
 
 

Saturday 19 April 2014

Set Wallpaper Android

Define Object 

File    myFolder;
    File file;
    WallpaperManager wallpaperManager ;

In Oncreat

boolean success = false;
        myFolder = new File("/sdcard/Diwali/");
        if( myFolder.exists() ){
            Log.d("", "FOLDER EXISTS");
        }else{

            success = myFolder.mkdir();

            if( success ){
                // Do something on success

            } else {
                // Do something else on failure
                throw new RuntimeException("File Error in writing new folder");
            }
        }

On Click Set Wallpaper


                SetWallpaper();
               
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                int height = displaymetrics.heightPixels;
                int width = displaymetrics.widthPixels;
                img.setDrawingCacheEnabled(true);
                Bitmap bmScreen = img.getDrawingCache();
                Bitmap scaled = Bitmap.createScaledBitmap(bmScreen, width, height, true);
               
               
                File myDir = new File(""+myFolder);   
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".jpg";
                 file = new File (myDir, fname);
                if (file.exists ()) file.delete ();
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    scaled.compress(Bitmap.CompressFormat.JPEG, 90, out);
                    out.flush();
                    out.close();

                    wallpaperManager = WallpaperManager.getInstance(GalleryActivity.this.getApplicationContext());

                } catch (Exception e) {
                    e.printStackTrace();
                }


Methods


private void SetWallpaper() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("Confirm");
        builder.setMessage("Set as Wallpaper ?");

        builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // Do nothing but close the dialog
                applyWallpaperFromFile(file);
                dialog.dismiss();
            }

        });

        builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
                dialog.dismiss();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
       
    }


    public static Bitmap decodeFile(File file, int reqWidth, int reqHeight){
        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getPath(), options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(file.getPath(), options);    
    }
       
    private static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }

        return inSampleSize;
    }  
   
    private void applyWallpaperFromFile(final File file)
    {
        Bitmap wallpaperImage = BitmapFactory.decodeFile(file.getPath());
        try {
            if((wallpaperManager.getDesiredMinimumWidth()>0)&&(wallpaperManager.getDesiredMinimumHeight()>0))
            {
                Bitmap blank = BitmapHelper.createNewBitmap(wallpaperManager.getDesiredMinimumWidth(), wallpaperManager.getDesiredMinimumHeight());
                Bitmap overlay = BitmapHelper.overlayIntoCentre(blank, wallpaperImage);

                wallpaperManager.setBitmap(overlay);

            }
            else
            {
                wallpaperManager.setBitmap(wallpaperImage);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                //Toast.makeText(FullSMSView.this,"Wallpaper set to:"+file.getName(), Toast.LENGTH_SHORT).show();
                Toast.makeText(GalleryActivity.this,"Set as a Wallpaper", Toast.LENGTH_SHORT).show();

            }
        });

    }
   
    public static class BitmapHelper {

        public static Bitmap overlayIntoCentre(Bitmap bmp1, Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, new Matrix(), null);//draw background bitmap

            //overlay the second in the centre of the first
            //(may experience issues if the first bitmap is smaller than the second, but then why would you want to overlay a bigger one over a smaller one?!)
            canvas.drawBitmap(bmp2, (bmp1.getWidth()/2)-(bmp2.getWidth()/2), 0, null);

            return bmOverlay;
        }

        public static Bitmap createNewBitmap(int width, int height)
        {
                    //create a blanks bitmap of the desired width/height
            return Bitmap.createBitmap(width, height, Config.ARGB_8888);
        }
        }


Njoy the Code!!