Search This Blog

Saturday, November 23, 2013

Get the Original file path From the Uri in the OnActivity Result

First of all pass the Intent to pick the image from the external storage.. or gelllary

Intent intent = new Intent(Intent.ACTION_PICK, 
      Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, 0);


OnActivityResult write the following code snippet

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  
  if(resultCode == RESULT_OK){
   
   image.setImageBitmap(null);
   
   //Uri return from external activity
   orgUri = data.getData();
   text1.setText("Returned Uri: " + orgUri.toString() + "\n");
   
   //path converted from Uri
   convertedPath = getRealPathFromURI(orgUri);
   text2.setText("Real Path: " + convertedPath + "\n");
   
   //Uri convert back again from path
   uriFromPath = Uri.fromFile(new File(convertedPath));
   text3.setText("Back Uri: " + uriFromPath.toString() + "\n");
  }
  
 }

Getting the real path of the Image using the Uri returned in OnActivityResult...

public String getRealPathFromURI(Uri contentUri) {
  String[] proj = { MediaStore.Images.Media.DATA };
  
  //This method was deprecated in API level 11
  //Cursor cursor = managedQuery(contentUri, proj, null, null, null);
  
  CursorLoader cursorLoader = new CursorLoader(
            this, 
            contentUri, proj, null, null, null);        
  Cursor cursor = cursorLoader.loadInBackground();
  
  int column_index = 
    cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
  cursor.moveToFirst();
  return cursor.getString(column_index); 
 }

List of Files in the Directory with specified type

Pass the File Directory in the method and extension if you want to get the files with different file extensions.

 private File[] getJpgFiles(File f){

  File[] files = f.listFiles(new FilenameFilter(){

   @Override
   public boolean accept(File dir, String filename) {
    return filename.toLowerCase().endsWith(".jpg");
   }});
  
  return files;
 }

Delete Directory with its all the inner file and Directories

This is the simple method to remove all the files and folders from the path in the SDcard.

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

fileOrDirectory.delete();
}

Unzipping the zip file with the location using ZipInputStream and ZIpEntry

Make a File with the name Decompress.java and add the following code snippet in it.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import android.util.Log;

/**
 * 
 * @author jon
 */
public class Decompress {
private String _zipFile;
private String _location;

public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;

_dirChecker("");
}

public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());

if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}

zin.closeEntry();
fout.close();
}

}
zin.close();
deleteDir(_zipFile);
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
}

}

private void _dirChecker(String dir) {
File f = new File(_location + dir);

if (!f.isDirectory()) {
f.mkdirs();
}
}

private void deleteDir(String dir) {
// TODO Auto-generated method stub
File f = new File(dir);
// Util.iLog("delete dir :" + dir);
if (f.exists()) {
f.delete();
}
}
}


Now call these class with the zip file location and unzip location with the following code snippet

Decompress d = new Decompress(zipfileloc, Unziploc);
d.unzip();

Download the large file from the server

Download the large file from the server asynchronously in android with the below code....

call this:

new DownloadFileAsync(YourActivity.this).execute();

And your DownloadFileAsync is as below:

class DownloadFileAsync extends AsyncTask<String, String, String> {

@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}

@Override
protected String doInBackground(String... aurl) {
int count;

try {

// URL url = new URL(DOWNLOAD URL);

URLConnection conexion = url.openConnection();
conexion.connect();

int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

InputStream input = new BufferedInputStream(url.openStream());
File filedir = new File(path);
// have the object build the directory structure, if needed.
filedir.mkdirs();
OutputStream output = new FileOutputStream(path + name + ".zip");

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile),
name);
output.write(data, 0, count);
}

output.flush();
output.close();
input.close();

} catch (Exception e) {
}
return null;

}

protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC", progress[0]);
mProgressDialog.setMessage("Downloading " + progress[1] + ".....");
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}

@Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
new UnzipFile(BookDownloadActivity.this, path + name + ".zip", path)
.execute();
}
}

@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file.....");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}


This is how you can download the whole file from the server or any other URLs.