Search This Blog

Saturday, November 23, 2013

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.

Thursday, August 29, 2013

Run the same AsyncTask after completing itself.

Create an object of the task and execute the same task as following.

UpdateCoin updatecoin = new UpdateCoin();

                    if (updatecoin.getStatus() == AsyncTask.Status.PENDING) {

                    }

                    if (updatecoin.getStatus() == AsyncTask.Status.RUNNING) {

                    }

                    if (updatecoin.getStatus() == AsyncTask.Status.FINISHED) {

                        Runnable myRunner = new Runnable() {
                            public void run() {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                                    new UpdateCoin().executeOnExecutor(
                                            AsyncTask.THREAD_POOL_EXECUTOR, coin,
                                            LevelUpBonus[level - 1]);
                                } else {
                                    new UpdateCoin().executeOnExecutor(
                                            AsyncTask.THREAD_POOL_EXECUTOR, coin,
                                            LevelUpBonus[level - 1]);
                                }
                            }
                        };
                        myHandler.post(myRunner);
                    }

Tuesday, July 16, 2013

Ecxecute two Different AsyncTask parallel in android

If you want to ecxecute the two different asynctask to be ecxecute parallelly then you shoul use the second async task ecxecution like below.  UpdateCoin is the Async task.         

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new UpdateCoin().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
mPref.getInt("UserCoin", 0), CalculatedCoin);
} else {
new UpdateCoin().execute(mPref.getInt("UserCoin", 0), CalculatedCoin);
}

Tuesday, June 4, 2013

Sorting the ArrayList by Name and Value in android

Sorting the ArrayList by String comparison by the Following code.

Collections.sort(name, new Comparator<YOURARRAYLISTNAME>() {
    @Override
    public int compare(Invitation lhs, Invitation rhs) {
     return lhs.getName().compareToIgnoreCase(rhs.getName());
    }
   });


You can also compare Arraylist by INTEGER value by following code:


Collections.sort(value, new Comparator<YOURARRAYLISTNAME>() {
    @Override
    public int compare(Invitation lhs, Invitation rhs) {
                        return (lhs.expenditure < rhs.expenditure ? 1 : -1);
    }
   });

Thursday, May 23, 2013

Validate the String for the Email


Here is the method for checking the String is email address or not.


private boolean checkemail(String emailstr) {
// TODO Auto-generated method stub
boolean isValid = false;
   String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
   CharSequence inputStr = emailstr;
   Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
   Matcher matcher = pattern.matcher(inputStr);
   if (matcher.matches()) {
       isValid = true;
   }
   return isValid;

}

For validate the String use following:

if(checkemail(emailstr)){
  // Here do with the Email string
}else{
  System.out.println("email String is not valid");
}

Thursday, May 9, 2013

Get the number of times app is used




 private SharedPreferences mPref;
public static final String PREFS_NAME = "YourPrefName";
int c;

in onCreate() write the following



  mPref = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
c = mPref.getInt("numRun", 0);
Log.i("TAG", "Number of count of open App:" + c);
c++;
mPref.edit().putInt("numRun", c).commit();
Log.i("TAG", "Number of count after commit of open App:" + c);