create internal db file android sqlite - android

I'm trying to create internal db file when data submit to database.when user enter values to textfields and click on the button,'SAMPLE.db' db file should create inside 'MYTEST' file on internal storage.this is my code.but it's not working.
-Main Activity oncreate-
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Id=mEDitTxt.getText().toString();
String Unm=mEDitTxt2.getText().toString();
insertconfig(Id, Unm);
DbBackup.copyDatabase(getApplicationContext());
}
});
-DBbackup-
public class DbBackup {
public static void copyDatabase(Context c) {
String DATABASE_NAME = "SAMPLE.db";
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
OutputStream myOutputInternal = null;
InputStream myInput = null;
Log.d("testing", " lots db path " + databasePath);
Log.d("testing", " lots db exist " + f.exists());
if (f.exists()) {
try {
File directoryIntenal = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/MYTEST/");
if (!directoryIntenal.exists())
directoryIntenal.mkdir();
myOutputInternal = new FileOutputStream(directoryIntenal.getAbsolutePath()
+ "/" + DATABASE_NAME);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutputInternal.write(buffer, 0, length);
}
myOutputInternal.flush();
} catch (Exception e) {
} finally {
try {
if (myOutputInternal != null) {
myOutputInternal.close();
myOutputInternal = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
}

Call this method when you want to export OR import your database ,
public class DbExportImport {
public static final String TAG = DbExportImport.class.getName();
/**
* Directory that files are to be read from and written to *
*/
public static final String PACKAGE_NAME = "com.vcs.androiddatabaseexample";
public static final String DATABASE_NAME = "crud.db";
public static final File DATA_DIRECTORY_DATABASE = new File(
Environment.getDataDirectory() + "/data/" + PACKAGE_NAME
+ "/databases/" + DATABASE_NAME);
public static final String DATA_DIRECTORY_DATABASE_PATH =
Environment.getDataDirectory() + "/data/" + PACKAGE_NAME
+ "/databases/" + DATABASE_NAME;
public static boolean exportSyncDbNew(String Filename, String FolderPath) {
if (!SdIsPresent())
return false;
File dbFile = DATA_DIRECTORY_DATABASE;
if (dbFile.exists()) {
// String filename = Filename+"_SAT.db";
File exportDir = new File(FolderPath);
if (!exportDir.exists()) {
exportDir.mkdirs();
}
File file = new File(exportDir, Filename);
Utils.printLoge(5, "#### exportDir", "-->" + FolderPath);
Utils.printLoge(5, "#### Filename", "-->" + Filename);
Utils.printLoge(5, "DATA_DIRECTORY_DATABASE", "-->" + DATA_DIRECTORY_DATABASE);
try {
if (!file.exists()) {
file.createNewFile();
copyFile(dbFile, file);
return true;
} else {
return false;
}
} catch (IOException e) {
//e.printStackTrace();
Constant.isFielCopeError = true;
Constant.fileCopeException = "Upload: " + Utils.ConvertExceptionToString(e);
return false;
}
} else {
Constant.isFielCopeError = true;
Constant.fileCopeException = "Upload: DB not available";
return false;
}
}
public static boolean restoreDownloadedDb(String FileName) {
if (!SdIsPresent())
return false;
File exportFile = DATA_DIRECTORY_DATABASE;
//File importFile = IMPORT_Downloaded_FILE;
File importFile = new File(Constant.ECTERNAL_STORAGE_APP_USER1, FileName);
if (exportFile.exists()) {
exportFile.delete();
// Log.e(TAG, "exportFile delete");
}
if (!importFile.exists()) {
// Log.d(TAG, "File does not exist");
return false;
}
try {
exportFile.createNewFile();
//copyFile(importFile, exportFile);
copyDataBase(importFile, exportFile);
return true;
} catch (IOException e) {
Utils.printLoge(5, "restoreDownloadedDb", "error-->" + e.getMessage().toString());
e.printStackTrace();
return false;
}
}

Related

Downloading and restore of sqlite database stored in google drive app folder

I have a database backup stored in app folder in the drive. Below is the code I have written.
public void startRestore(View view)
{
int EXTERNAL_WRITE_PERMISSION = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M)
{
if(EXTERNAL_WRITE_PERMISSION != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
Snackbar.make(mLayout, "Write permission is required",
Snackbar.LENGTH_INDEFINITE).setAction("OK", new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request the permission
ActivityCompat.requestPermissions(BackupActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
}
}).show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_STORAGE);
}
}
}
if (backupExists())
{
Log.d("RESTORE: ", "Started restore");
final String driveFileID = sharedPreferences.getString("dbBackupDriveFileID", "");
final DriveFile driveFile = DriveId.decodeFromString(driveFileID).asDriveFile();
Log.d("RESTORE_FileID: ", driveFileID);
final Task<DriveContents> openFileTask = mDriveResourceClient.openFile(driveFile, DriveFile.MODE_READ_ONLY);
openFileTask.continueWithTask(new Continuation<DriveContents, Task<Void>>()
{
#Override
public Task<Void> then(#NonNull Task<DriveContents> task) throws Exception
{
Log.d("RESTORE: ", "open File task");
DriveContents driveContents = task.getResult();
//TODO download file an add to database
InputStream inputStream = driveContents.getInputStream();
byte[] buf = new byte[8192];
int c = 0;
String baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = DatabaseHelper.DATABASE_NAME;
Log.d("RESTORE: ", baseDir + "/" +fileName);
File f = new File(baseDir+File.pathSeparator+fileName);
if(f.canWrite())
{
Log.d("RESTORE: ", "File writable");
OutputStream outputStream = new FileOutputStream(f);
while ((c = inputStream.read(buf, 0, buf.length)) > 0)
{
outputStream.write(buf, 0, c);
outputStream.flush();
}
outputStream.close();
}
else
{
Log.d("RESTORE: ", "File not writable");
}
return mDriveResourceClient.discardContents(driveContents);
}
})
.addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception e)
{
}
});
}
else
{
Toast.makeText(this, "Backup does not exists", Toast.LENGTH_SHORT).show();
}
}
In the above code the the control always reaches to Log.d("RESTORE: ", "File not writable");. I have the write permissions defined in the manifest and also runtime permission is granted. Also there is no error in the log.
Below is the backup function for reference.
public void startBackup(View view)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
final File currentDB = this.getDatabasePath(DatabaseHelper.DATABASE_NAME);
Log.d("DATABASE: ", currentDB.getAbsolutePath());
Log.d("DATABASE: ", currentDB.getName());
progressDialog.setMessage("Backing Up!!!!");
progressDialog.show();
final Task<DriveFolder> appFolderTask = mDriveResourceClient.getAppFolder();
final Task<DriveContents> createContentsTask = mDriveResourceClient.createContents();
Tasks.whenAll(appFolderTask, createContentsTask)
.continueWithTask(new Continuation<Void, Task<DriveFile>>()
{
#Override
public Task<DriveFile> then(#NonNull Task<Void> task) throws Exception
{
DriveFolder parent = appFolderTask.getResult();
DriveContents contents = createContentsTask.getResult();
InputStream inputStream = null;
try
{
inputStream = new FileInputStream(currentDB);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
OutputStream outputStream = contents.getOutputStream();
int c = 0;
byte[] buf = new byte[8192];
if (inputStream != null)
{
while ((c = inputStream.read(buf, 0, buf.length)) > 0)
{
outputStream.write(buf, 0, c);
outputStream.flush();
}
outputStream.close();
}
else
{
Toast.makeText(BackupActivity.this, "Some error occurred", Toast.LENGTH_SHORT).show();
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setMimeType("application/x-sqlite3")
.setTitle(currentDB.getName())
.build();
return mDriveResourceClient.createFile(parent, changeSet, contents);
}
})
.addOnSuccessListener(this, new OnSuccessListener<DriveFile>() {
#Override
public void onSuccess(DriveFile driveFile)
{
progressDialog.dismiss();
String driveFileID = driveFile.getDriveId().encodeToString();
String dateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("dbBackupDriveFileID", driveFileID);
editor.putString("lastDbBackupTime", dateTime);
editor.apply();
Log.d("DRIVE_FILE", driveFileID);
String d = getString(R.string.last_backup) + dateTime;
textView.setText(d);
Toast.makeText(BackupActivity.this, "Backup Successful. File "+driveFile.getDriveId()
.encodeToString(), Toast.LENGTH_LONG).show();
}
})
.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
progressDialog.dismiss();
Log.e("DRIVE ", "Unable to create file", e);
Toast.makeText(BackupActivity.this, "Unable to backup", Toast.LENGTH_SHORT).show();
}
});
}
Instead of using the File f = new File(baseDir+File.pathSeparator+fileName); I replaced the File usage with an FileOutputStream.
Modified part of the restore function:
DriveContents driveContents = task.getResult();
//TODO download file an add to database
InputStream inputStream = driveContents.getInputStream();
byte[] buf = new byte[8192];
int c = 0;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
Log.d("RESTORE: ", "External DIR mounted");
String baseDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
String fileName = DatabaseHelper.DATABASE_NAME;
String fileFullName = baseDir + File.separator + fileName;
Log.d("RESTORE: ", fileFullName);
FileOutputStream outputStream;
outputStream = new FileOutputStream(fileFullName, false);
while ((c = inputStream.read(buf, 0, buf.length)) > 0) {
outputStream.write(buf, 0, c);
outputStream.flush();
}
outputStream.close();
}
else
{
Log.d("RESTORE: ", "External DIR not mounted");
}
This solved my issue.
The answer could be as simple as adding f.mkdirs() immediately after File f = new File(baseDir+File.pathSeparator+fileName); and before if(f.canWrite()).
However there are numerous reasons why canWrite can return false, So you should check the STATE (probably before you try canWrite)
Personally I utilise the following rather long winded code :-
class StoreData {
private String directory; //Note built internally and includes subdirectory
private String subdirectory;
private String filename;
private boolean mounted;
private boolean inerror;
private boolean fileexists;
private boolean direxists;
private long errorcode;
private ArrayList<String> errorlist = new ArrayList<>();
private ArrayList<File> otherfilesindirectory = new ArrayList<>();
// Need to be aware of the API
#SuppressWarnings("unused")
public static final int API_VERSION = Build.VERSION.SDK_INT;
private static final long UNMOUNTED = 1;
private static final long FILEIOERR = 2;
private static final long READERR = 4;
private static final String NEWLINE = "\r\n";
/**
* Sole Constructor for a StoreData object
* Note instantiating creates but the deletes a file, assuming that
* no prior errors left the instance in an unusable state (as initially set)
* Note instantiating, if existcheck (3rd param) is true, does not create
* and delete the file, rather it checks that the file exists
* typically for reading an existing file.
*
* #param subdirectory - Sub directory in which to create file
* #param filename - the file name where actual data will be stored
* #param existcheck - whether or not to check for the existence of the file
*
* Note!! existcheck, if true, will not try to create the file
*/
public StoreData(String subdirectory, #SuppressWarnings("SameParameterValue") String filename, boolean existcheck) {
fileexists = false;
direxists = false;
mounted = false;
inerror = false;
errorcode = 0;
this.directory = "";
this.subdirectory = subdirectory;
this.filename = filename;
// External Storage must be mounted.
String chkmnt = Environment.getExternalStorageState();
if(!(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
switch (Environment.getExternalStorageState()) {
case Environment.MEDIA_SHARED : {
errorlist.add(
"Although External Storage is present." +
" It cannot be used as it's in use via USB." +
"\nDisconnect the USB cable and then try again."
);
break;
}
case Environment.MEDIA_REMOVED : {
errorlist.add(
"External Storage is not present." +
"\nInsert an SD Card."
);
break;
}
case Environment.MEDIA_EJECTING : {
errorlist.add(
"External Storage is being ejected." +
"\nRe-insert the SD Card."
);
break;
}
case Environment.MEDIA_NOFS : {
errorlist.add(
"External Storage is blank or does not have the correct" +
" filesystem present." +
"\nUse a valid SDCard."
);
break;
}
case Environment.MEDIA_BAD_REMOVAL : {
errorlist.add(
"External Storage was removed incorrectly." +
"\nRe-insert the SD Card, if this fails then" +
" try restarting the device."
);
break;
}
case Environment.MEDIA_CHECKING : {
errorlist.add(
"External Storage is unavailable as it is being checked." +
"\nTry again."
);
}
case Environment.MEDIA_MOUNTED_READ_ONLY : {
errorlist.add(
"External Storage is READ ONLY." +
"\nInsert an SD card that is not protected."
);
}
case Environment.MEDIA_UNKNOWN : {
errorlist.add(
"External Storage state is UNKNOWN." +
"\ntry a different SD Card."
);
}
case Environment.MEDIA_UNMOUNTABLE : {
errorlist.add(
"External Storage cannot be mounted." +
"\nTry re-inserting the SD Card or using a different SD Card."
);
}
case Environment.MEDIA_UNMOUNTED : {
errorlist.add(
"External Storage is not mounted." +
"\nTry re-inserting the SD Card or using a different SD Card."
);
}
default: {
errorlist.add(
"Undefined Error"
);
}
}
this.errorcode = UNMOUNTED;
return;
} else {
this.mounted = true;
}
// Get the required directory and specified sub directory
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),subdirectory);
this.directory = dir.getPath();
// If existcheck is true check that the directories exist
if (existcheck && dir.exists()) {
direxists = true;
}
// If the directories do not exist try to create them and redo check
// Note! existcheck is more for file level so always try to create
// directories
else {
boolean x = dir.mkdirs();
if(dir.exists()) {
direxists = true;
}
}
if(direxists) {
refreshOtherFilesInDirectory();
}
// File level
File f = new File(directory,filename);
// Check if the file exists if requested and return if it does
if (existcheck) {
if (f.exists()) {
fileexists = true;
}
return;
}
try {
boolean x = f.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
this.errorcode = FILEIOERR ;
errorlist.add(
"File Error " + e.getMessage()
);
return;
}
boolean x = f.delete();
}
#SuppressWarnings({"ConstantConditions", "UnusedReturnValue"})
public boolean refreshOtherFilesInDirectory() {
boolean rv = true;
File dir = new File(directory);
File[] dirlist = dir.listFiles();
if((dirlist.length) > 0) {
// Sort the list
Arrays.sort(dirlist, new Comparator<File>() {
#Override
public int compare(File object1, File object2) {
return object1.getName().compareTo(object2.getName());
}
});
otherfilesindirectory.clear();
for (File aDirlist : dirlist) {
if (!(aDirlist.getName().equals(this.filename))) {
otherfilesindirectory.add(aDirlist);
}
}
}
return rv;
}
/**
* writeData - Write data to the file from String Arraylist passed
* Note!! a linefeed is added to each string
* #param datatowrite - strng ArrayList holding data to write
* #return result flag
*/
#SuppressWarnings("unused")
public boolean writeData(ArrayList<String> datatowrite) {
// Check that this instance is OK
if (!this.isOK()) {
this.errorlist.add(
"\nError prior to call to writeData method."
);
return false;
}
// Prepare to write
this.errorlist.clear();
File f = new File(this.directory,File.separator + this.filename);
try {
boolean x = f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(fos);
for (int i = 0; i < datatowrite.size(); i++) {
osw.write(datatowrite.get(i) + NEWLINE);
}
osw.flush();
osw.close();
fos.flush();
fos.close();
this.fileexists = true;
}
catch (IOException e) {
e.printStackTrace();
this.errorcode = FILEIOERR;
errorlist.add(
"File Error " + e.getMessage()
);
return false;
}
return true;
}
/**
* readData - Populate a String ArrayList from the data in the file
* Note! Assumes linefeeds in the file separate strings of data
* #return - result flag
*/
#SuppressWarnings("unused")
public ArrayList<String> readData() {
ArrayList<String> rv = new ArrayList<>();
if(!this.isOKandExists()) {
this.errorlist.add(
"\nError prior to call to readData method or the file doesn't exist."
);
this.errorcode = READERR;
return rv;
}
this.errorlist.clear();
File f = new File(this.directory,File.separator + this.filename);
try {
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
rv.add(line);
}
}
catch (IOException e) {
e.printStackTrace();
this.errorcode = READERR;
errorlist.add(
"File Read Error" + e.getMessage()
);
return rv;
}
return rv;
}
/**
* isOK - Check if object is usable
* #return true if OK else false
*/
public boolean isOK() {
return !(errorcode != 0 || !mounted || inerror);
}
/**
* exists = Check if the file exists
* #return - Result of check
*/
#SuppressWarnings("unused")
public boolean exists() {
return this.fileexists;
}
public boolean isOKandExists() {
return this.isOK() && this.fileexists;
}
/**
* Return a string displaying the instances details
* #return string displaying object's members
*/
public String Display() {
String rv;
rv = "Directory path=" + directory + "\n" +
"SubDirectory=" + subdirectory + "\n" +
"Filename=" + filename + "\n" +
"Mounted =" + Boolean.toString(mounted) + "\n" +
"Directory Exists=" + Boolean.toString(this.direxists) + "\n" +
"File Exists=" + Boolean.toString(this.fileexists) + "\n" +
"In Error=" + Boolean.toString(inerror) + "\n" +
"Last Error Code=" + Long.toString(errorcode);
return rv;
}
#SuppressWarnings("unused")
public String DisplayWithOtherFiles() {
String rv;
rv = this.Display() + "\nOther Files in Directory (" + this.directory + ") ";
for(int i = 0; i < otherfilesindirectory.size(); i++) {
rv = rv + "\n\t" + otherfilesindirectory.get(i).getName();
}
return rv;
}
/**
* Retrieve generated error messages. if any
* #return sting comprised of all error messages generated
*/
#SuppressWarnings("unused")
public String getErrorMessages() {
String rv = "";
for(int i = 0; i < errorlist.size(); i++) {
rv = rv + errorlist.get(i);
}
return rv;
}
/**
* Method: getDirectory - get the backup directory as a String
* #return Directory as a String
*/
public String getDirectory() {
return this.directory;
}
/**
* Method: getFilename - get the filename of the object as a String
* #return Filename as a String
*/
#SuppressWarnings("unused")
public String getFilename() {
return this.filename;
}
/**
* Method: getSubDirectory - get the sub-directory as a string
* #return Sub-Directory as a String
*/
#SuppressWarnings("unused")
public String getSubDirectory() {
return this.subdirectory;
}
/**
* Method: getFilesInDirectory - return an ArrayList of type File
* #return List of files in the directory as an ArrayList<File>
*/
public ArrayList<File> getFilesInDirectory() {
return this.otherfilesindirectory;
}
}

How to run apkfile in application

This code is running an apkfile after download from webserver.
But..
When the apkfile runs, it prints this message.
-Parse error
"There is a problem parsing the package."
When i run apkfile after copy to device, it did not print message.
How can I solve this ?
p.s) starting method is skinDownload(filename).
String File_Name = "";
String File_extend = "";
String fileURL = "http://URL/";
String Save_Path = "/data/data/kr.appsol.util.calc.formcalc/themes";
DownloadThread dThread;
ProgressDialog downDialog = null;
private void skinDownload(String filename){
File_Name = filename + ".apk";
File_extend = "apk";
File dir = new File(Save_Path);
if (!dir.exists()) {
dir.mkdir();
}
if (new File(Save_Path + "/" + File_Name).exists() == false) {
downDialog = ProgressDialog.show(Activity_SkinList.this, "", getString(R.string.setting_skin_downloading));
downDialog.show();
dThread = new DownloadThread(fileURL + "/" + File_Name,
Save_Path + "/" + File_Name);
dThread.start();
} else {
showDownloadFile();
}
}
class DownloadThread extends Thread {
String ServerUrl;
String LocalPath;
DownloadThread(String serverPath, String localPath) {
ServerUrl = serverPath;
LocalPath = localPath;
}
#Override
public void run() {
URL imgurl;
int Read;
try {
imgurl = new URL(ServerUrl);
HttpURLConnection conn = (HttpURLConnection) imgurl
.openConnection();
int len = conn.getContentLength();
byte[] tmpByte = new byte[len];
InputStream is = conn.getInputStream();
File file = new File(LocalPath);
FileOutputStream fos = new FileOutputStream(file);
for (;;) {
Read = is.read(tmpByte);
if (Read <= 0) {
break;
}
fos.write(tmpByte, 0, Read);
}
is.close();
fos.close();
conn.disconnect();
} catch (MalformedURLException e) {
Log.e("ERROR1", e.getMessage());
} catch (IOException e) {
Log.e("ERROR2", e.getMessage());
e.printStackTrace();
}
mAfterDown.sendEmptyMessage(0);
}
}
Handler mAfterDown = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
downDialog.dismiss();
// run
showDownloadFile();
}
};
private void showDownloadFile() {
File apkFile = new File(Save_Path + "/" + File_Name);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
startActivity(intent);
}
You probably need to flush the stream before closing it:
fos.flush();
fos.close();

unzippping of zipped files fails for android using code which are zipped from Mac system

In my application i am downloading zipped from a server and extracting the files through code here but the zip files contains .DS_store file and so my unzipping fails . Is there a way to avoid it.
/*/////
public class Decompress {
private String _zipFile;
private String _location;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public boolean 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 {
byte[] buffer = new byte[1024];
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
// for (int c = zin.read(); c != -1; c = zin.read(buffer,0,1024)) {
// fout.write(buffer,0,c);
// }
int c;
while (( c = zin.read(buffer,0,1024)) >= 0) {
fout.write(buffer,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
return false;
}
return true;
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
////
*/
use this code
public class ZipHelper
{
boolean zipError=false;
public boolean isZipError() {
return zipError;
}
public void setZipError(boolean zipError) {
this.zipError = zipError;
}
public boolean unzip(String archive, File outputDir)
{
try {
Log.d("control","ZipHelper.unzip() - File: " + archive);
ZipFile zipfile = new ZipFile(archive);
for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
return true;
}
catch (Exception e) {
Log.d("control","ZipHelper.unzip() - Error extracting file " + archive+": "+ e);
setZipError(true);
return false;
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException
{
if (entry.isDirectory()) {
createDirectory(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()){
createDirectory(outputFile.getParentFile());
}
Log.d("control","ZipHelper.unzipEntry() - Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
}
catch (Exception e) {
Log.d("control","ZipHelper.unzipEntry() - Error: " + e);
setZipError(true);
}
finally {
outputStream.close();
inputStream.close();
}
}
private void createDirectory(File dir)
{
Log.d("control","ZipHelper.createDir() - Creating directory: "+dir.getName());
if (!dir.exists()){
if(!dir.mkdirs()) throw new RuntimeException("Can't create directory "+dir);
}
else Log.d("control","ZipHelper.createDir() - Exists directory: "+dir.getName());
}
}
call this class like this
final String exportDirectory = Environment.getExternalStorageDirectory().getAbsolutePath()
+"/destination file/name/";
final String exportDirectoryArchivefile = Environment.getExternalStorageDirectory().getAbsolutePath()
+"/original/file name/"+name;
final File exportDirectoryFilepath = new File(exportDirectory);
exportDirectoryFilepath.mkdirs();
final File exportDirectoryFilepathArchive = new File(exportDirectoryArchivefile);
boolean flag_unzip =zh.unzip(exportDirectoryArchivefile, exportDirectoryFilepath);

Android - Unzip a folder?

I have a zip folder on my SD card, how do i unzip the folder (within my application code) ?
I am using a modified version of Beginner's method that extends AsyncTask and can update Observers on the main thread. Byte by byte compression is extremely slow and should be avoided. Instead a more efficient approach is to copy large chunks of data to the output stream.
package com.blarg.webviewscroller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Observable;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.os.AsyncTask;
import android.util.Log;
public class UnZipper extends Observable {
private static final String TAG = "UnZip";
private String mFileName, mFilePath, mDestinationPath;
public UnZipper (String fileName, String filePath, String destinationPath) {
mFileName = fileName;
mFilePath = filePath;
mDestinationPath = destinationPath;
}
public String getFileName () {
return mFileName;
}
public String getFilePath() {
return mFilePath;
}
public String getDestinationPath () {
return mDestinationPath;
}
public void unzip () {
String fullPath = mFilePath + "/" + mFileName + ".zip";
Log.d(TAG, "unzipping " + mFileName + " to " + mDestinationPath);
new UnZipTask().execute(fullPath, mDestinationPath);
}
private class UnZipTask extends AsyncTask<String, Void, Boolean> {
#SuppressWarnings("rawtypes")
#Override
protected Boolean doInBackground(String... params) {
String filePath = params[0];
String destinationPath = params[1];
File archive = new File(filePath);
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, destinationPath);
}
} catch (Exception e) {
Log.e(TAG, "Error while extracting file " + archive, e);
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
setChanged();
notifyObservers();
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
Log.v(TAG, "Extracting: " + entry);
BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
if (dir.exists()) {
return;
}
Log.v(TAG, "Creating dir " + dir.getName());
if (!dir.mkdirs()) {
throw new RuntimeException("Can not create dir " + dir);
}
}
}
}
It is used by a class that implements Observer, such as:
private void unzipWebFile(String filename) {
String unzipLocation = getExternalFilesDir(null) + "/unzipped";
String filePath = Environment.getExternalStorageDirectory().toString();
UnZipper unzipper = new UnZipper(filename, filePath, unzipLocation);
unzipper.addObserver(this);
unzipper.unzip();
}
Your observer will get an update(Observable observable, Object data) callback when the unzip finishes.
static Handler myHandler;
ProgressDialog myProgress;
public void unzipFile(File zipfile) {
myProgress = ProgressDialog.show(getContext(), "Extract Zip",
"Extracting Files...", true, false);
File zipFile = zipfile;
String directory = null;
directory = zipFile.getParent();
directory = directory + "/";
myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// process incoming messages here
switch (msg.what) {
case 0:
// update progress bar
myProgress.setMessage("" + (String) msg.obj);
break;
case 1:
myProgress.cancel();
Toast toast = Toast.makeText(getContext(),
"Zip extracted successfully",
Toast.LENGTH_SHORT);
toast.show();
provider.refresh();
break;
case 2:
myProgress.cancel();
break;
}
super.handleMessage(msg);
}
};
Thread workthread = new Thread(new UnZip(zipFile, directory));
workthread.start();
}
public class UnZip implements Runnable {
File archive;
String outputDir;
public UnZip(File ziparchive, String directory) {
archive = ziparchive;
outputDir = directory;
}
public void log(String log) {
Log.v("unzip", log);
}
#SuppressWarnings("unchecked")
public void run() {
Message msg;
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
msg = new Message();
msg.what = 0;
msg.obj = "Extracting " + entry.getName();
myHandler.sendMessage(msg);
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
}
#SuppressWarnings("unchecked")
public void unzipArchive(File archive, String outputDir) {
try {
ZipFile zipfile = new ZipFile(archive);
for (Enumeration e = zipfile.entries();
e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, outputDir);
}
} catch (Exception e) {
log("Error while extracting file " + archive);
}
}
private void unzipEntry(ZipFile zipfile, ZipEntry entry,
String outputDir) throws IOException {
if (entry.isDirectory()) {
createDir(new File(outputDir, entry.getName()));
return;
}
File outputFile = new File(outputDir, entry.getName());
if (!outputFile.getParentFile().exists()) {
createDir(outputFile.getParentFile());
}
log("Extracting: " + entry);
BufferedInputStream inputStream = new
BufferedInputStream(zipfile
.getInputStream(entry));
BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream(outputFile));
try {
IOUtils.copy(inputStream, outputStream);
} finally {
outputStream.close();
inputStream.close();
}
}
private void createDir(File dir) {
log("Creating dir " + dir.getName());
if (!dir.mkdirs())
throw new RuntimeException("Can not create dir " + dir);
}
}
This is what worked for me thanks people
just "addon" for #rich.e answer:
in doInBackground() after iterating through ZipEtries you should close the file, because sometimes you want do delete the file after unzipping it and it throws an exception if file was not closed:
try {
ZipFile zipfile = new ZipFile(archive);
int entries = zipfile.size();
int total = 0;
if(onZipListener != null)
onZipListener.onUncompressStart(archive);
for (Enumeration<?> e = zipfile.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(onZipListener != null)
onZipListener.onUncompressProgress(archive, (int) (total++ * 100 / entries));
unzipEntry(zipfile, entry, path);
}
zipfile.close();
} catch (Exception e) {
e.printStackTrace();
}

File operation in android

I am new to android platform. I need to create a text file in android. Please let me know how to perform this task in android. I have written a code that is working fine in java but not in android. Please help me on this....the sample code that ihave written is :-
try
{
DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.txt", true));
dos.writeBytes(dataLine);
dos.close();
}
catch (FileNotFoundException ex) {}
the above code snippet is working fine in java but not in android :(
Thanks,
Ashish
The Android Dev Guide explains it nicely:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
If you want the files you create to be visible to the outside world, use external storage. But as I said in the comment, make sure you're "being a good citizen". These files stick around even after the user uninstalls your app.
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
/**
* Static methods used for common file operations.
*
* #author Carl Hartung (carlhartung#gmail.com)
*/
public class FileUtils {
private final static String t = "FileUtils";
// Used to validate and display valid form names.
public static final String VALID_FILENAME = "[ _\\-A-Za-z0-9]*.x[ht]*ml";
// Storage paths
public static final String FORMS_PATH = Environment.getExternalStorageDirectory() + "/odk/forms/";
public static final String INSTANCES_PATH = Environment.getExternalStorageDirectory() + "/odk/instances/";
public static final String CACHE_PATH = Environment.getExternalStorageDirectory() + "/odk/.cache/";
public static final String TMPFILE_PATH = CACHE_PATH + "tmp.jpg";
public static ArrayList<String> getValidFormsAsArrayList(String path) {
ArrayList<String> formPaths = new ArrayList<String>();
File dir = new File(path);
if (!storageReady()) {
return null;
}
if (!dir.exists()) {
if (!createFolder(path)) {
return null;
}
}
File[] dirs = dir.listFiles();
for (int i = 0; i < dirs.length; i++) {
// skip all the directories
if (dirs[i].isDirectory())
continue;
String formName = dirs[i].getName();
formPaths.add(dirs[i].getAbsolutePath());
}
return formPaths;
}
public static ArrayList<String> getFoldersAsArrayList(String path) {
ArrayList<String> mFolderList = new ArrayList<String>();
File root = new File(path);
if (!storageReady()) {
return null;
}
if (!root.exists()) {
if (!createFolder(path)) {
return null;
}
}
if (root.isDirectory()) {
File[] children = root.listFiles();
for (File child : children) {
boolean directory = child.isDirectory();
if (directory) {
mFolderList.add(child.getAbsolutePath());
}
}
}
return mFolderList;
}
public static boolean deleteFolder(String path) {
// not recursive
if (path != null && storageReady()) {
File dir = new File(path);
if (dir.exists() && dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.delete()) {
Log.i(t, "Failed to delete " + file);
}
}
}
return dir.delete();
} else {
return false;
}
}
public static boolean createFolder(String path) {
if (storageReady()) {
boolean made = true;
File dir = new File(path);
if (!dir.exists()) {
made = dir.mkdirs();
}
return made;
} else {
return false;
}
}
public static boolean deleteFile(String path) {
if (storageReady()) {
File f = new File(path);
return f.delete();
} else {
return false;
}
}
public static byte[] getFileAsBytes(File file) {
byte[] bytes = null;
InputStream is = null;
try {
is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
// Create the byte array to hold the data
bytes = new byte[(int) length];
// Read in the bytes
int offset = 0;
int read = 0;
try {
while (offset < bytes.length && read >= 0) {
read = is.read(bytes, offset, bytes.length - offset);
offset += read;
}
} catch (IOException e) {
Log.e(t, "Cannot read " + file.getName());
e.printStackTrace();
return null;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
try {
throw new IOException("Could not completely read file " + file.getName());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return bytes;
} catch (FileNotFoundException e) {
Log.e(t, "Cannot find " + file.getName());
e.printStackTrace();
return null;
} finally {
// Close the input stream
try {
is.close();
} catch (IOException e) {
Log.e(t, "Cannot close input stream for " + file.getName());
e.printStackTrace();
return null;
}
}
}
public static boolean storageReady() {
String cardstatus = Environment.getExternalStorageState();
if (cardstatus.equals(Environment.MEDIA_REMOVED)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTED)
|| cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
return false;
} else {
return true;
}
}
public static String getMd5Hash(File file) {
try {
// CTS (6/15/2010) : stream file through digest instead of handing it the byte[]
MessageDigest md = MessageDigest.getInstance("MD5");
int chunkSize = 256;
byte[] chunk = new byte[chunkSize];
// Get the size of the file
long lLength = file.length();
if (lLength > Integer.MAX_VALUE) {
Log.e(t, "File " + file.getName() + "is too large");
return null;
}
int length = (int) lLength;
InputStream is = null;
is = new FileInputStream(file);
int l = 0;
for (l = 0; l + chunkSize < length; l += chunkSize) {
is.read(chunk, 0, chunkSize);
md.update(chunk, 0, chunkSize);
}
int remaining = length - l;
if (remaining > 0) {
is.read(chunk, 0, remaining);
md.update(chunk, 0, remaining);
}
byte[] messageDigest = md.digest();
BigInteger number = new BigInteger(1, messageDigest);
String md5 = number.toString(16);
while (md5.length() < 32)
md5 = "0" + md5;
is.close();
return md5;
} catch (NoSuchAlgorithmException e) {
Log.e("MD5", e.getMessage());
return null;
} catch (FileNotFoundException e) {
Log.e("No Cache File", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Problem reading from file", e.getMessage());
return null;
}
}
}
Try this
final File sdcard=Environment.getExternalStorageDirectory();
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
File path=new File(sdcard,"textfile.txt");
try {
BufferedWriter wr=new BufferedWriter(new FileWriter(path));
wr.write("Your Text Here");
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also you need to add following permission to your manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Categories

Resources