Broadcast Receiver using background process - android

how to copy images from one folder to another in sdcard or local storage using broadcast receiver in background process.
I have tried this link
Here is my code:
public class Photoimport extends Activity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.photoimport);
button = (Button) findViewById(R.id.photoimport);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// File storageDir = new File("/storagescfsf/emulated/0/demo/");
File rootsd = Environment.getExternalStorageDirectory();
File srcFolder = new File(rootsd.getAbsolutePath()
+ "/Imported/");
if (srcFolder != getAbsolutePath()) {
// Toast.makeText(getApplicationContext(),"Found:" + "\n" +
// rootsd + "/import/", 1000).show();
// File srcFolder = new File("/mnt/sdcard/Imported");
// Check list of images //
String files[] = srcFolder.list();
try {
if (files.length <= 0) {
// System.out.println("No Images found");
Toast.makeText(
getApplicationContext(),
"No Images Found at " + srcFolder
+ "\n Please import and try again.",
1000).show();
finish();
return;
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// error finish activity
System.exit(0);
}
// if (files.length <= 0) {
// //System.out.println("No Images found");
// Toast.makeText(getApplicationContext(),
// "No Images Found at "+srcFolder+"\n Please import and try again.",
// 1000)
// .show();
// return;
// }
File Photosync_dir = new File(rootsd.getAbsolutePath()
+ "/Photosync");
if (!Photosync_dir.exists()) {
if (Photosync_dir.mkdir()) {
// directory is created;
// Toast.makeText(getApplicationContext(),"Folder Created",
// 1000).show();
} else {
Toast.makeText(
getApplicationContext(),
"Unable to create Folder at"
+ Photosync_dir.getAbsolutePath(),
1000).show();
return;
}
}
// Toast.makeText(getApplicationContext(),direct +
// " exists", 1000).show();
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss",
d.getTime());
File dir = new File(Photosync_dir + "/" + s);
if (!dir.exists()) {
if (dir.mkdirs()) {
System.out.println("newFolder created");
} else {
System.out.println("newFolder is not created");
}
File destFolder = new File(Photosync_dir
.getAbsolutePath() + "/" + s);
// make sure source exists
if (!srcFolder.exists()) {
System.out.println("Directory does not exist.");
// just exit
System.exit(0);
} else {
try {
cutFolder(srcFolder, destFolder);
} catch (IOException e) {
e.printStackTrace();
// error, just exit
System.exit(0);
}
}
// DeleteRecursive(dcim);
// deleteFiles(dcim.getAbsolutePath());
System.out.println("Done");
Toast.makeText(
getApplicationContext(),
files.length
+ " file(s) have been imported to "
+ destFolder.getAbsolutePath(), 1000)
.show();
}
} else {
Toast.makeText(getApplicationContext(),
"Directory Not Found at " + srcFolder, 1000).show();
}
}
private File getAbsolutePath() {
// TODO Auto-generated method stub
return null;
}
});
}
void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
DeleteRecursive(child);
if (fileOrDirectory.delete()) {
System.out.println("deleted");
}
}
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) {
}
}
}
public static void cutFolder(File src, File dest) throws IOException {
if (src.isDirectory()) {
// if directory not exists, create it
if (!dest.exists()) {
dest.mkdir();
System.out.println("Directory copied from " + src + " to "
+ dest);
}
// list all the directory contents
String files[] = src.list();
for (String file : files) {
// construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
// recursive copy
cutFolder(srcFile, destFile);
}
} else {
// if file, then copy it
// Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
deleteFiles(src.getAbsolutePath());
// boolean deleted = src.getAbsoluteFile().delete();
// if (deleted){
// System.out.println("file has been deleted from "+src.getAbsolutePath());
// }
// src.delete();
// src.renameTo(dest);
}
}
}

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;
}
}

Add res/raw folder content file (video) to external SD folder

The idea is I want to put the content/s of my res/raw folder to external sd folder named "myFolder".
my way is that I used Uri to access the video file in res/raw and used FileOutputStream and its not working, Is my way possible?
*I already have the permissions needed to READ and WRITE to external sd, and it is placed correclty in manifest.
CODE IS BELOW, THANK YOU
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String basepath = extStorageDirectory + "/myFolder/";
Uri UriPath=Uri.parse
("android.resource://com.example.videoplayer.videoplayer/" + R.raw.video1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_videoplayer);
File videodir= new File(basepath);
if (!videodir.exists()) {
videodir.mkdirs();
Toast.makeText(getApplicationContext(),
"Directory created!", Toast.LENGTH_LONG)
.show();
}else{
Toast.makeText(getApplicationContext(),
"Directory exists!", Toast.LENGTH_LONG)
.show();
}
File file = new File (basepath, "android.resource://com.example.videoplayer.videoplayer/" + R.raw.video1); //Im not sure if the code reaches the video1 file
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file); //this line doesnt work
Toast.makeText(getApplicationContext(),
"File created!", Toast.LENGTH_LONG)
.show();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"File error!", Toast.LENGTH_LONG)
.show();
}
}
private void copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = "/data/data/" + this.getPackageName() + "/" + path;
File dir = new File(fullPath);
if (!dir.exists())
dir.mkdir();
for (int i = 0; i < assets.length; ++i) {
copyFileOrDir(path + "/" + assets[i]);
}
}
} catch (IOException ex) {
Log.e("tag", "I/O Exception", ex);
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(filename);
String newFileName = "/data/data/" + this.getPackageName() + "/" + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
}
To use above code call function with copyFileOrDir("myFolder");

how do i perform method for all iteration of for loop

my code just delete 1st file using button click but i want to delete and unhide all images using for loop if this statement is true if(CheckArr[i] == true) but my code just perform only first index file ot all checked file is delete only 1st one is delete what do i do? how do i delete and copy all checked item? how do i customize my for loop??
unhide.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < CheckArr.length; i++) {
if (CheckArr[i] == true) {
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db .selectQuery("SELECT path FROM Photos where name ='"+
currentFiles[i].getName() + "'");
Bitmap bitmap = decodeFile.decodeFile(new File(root + "/"+ currentFiles[i].getName()));
try {
FileOutputStream outputStream = new FileOutputStream(new
File(DataC.getString(DataC.getColumnIndex("path"))));
outputStream.write(decodeFile.getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(root + "/" + currentFiles[i].getName());
file.delete();
inflateListView(currentFiles);
DataC.close();
db.close();
}
}
I would do my loop differently. I'd only open the database once, and I'd check to see if the intermediate steps are working.
This is more what I'd recommend:
unhide.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
db.createDataBase();
for (int i = 0; i < CheckArr.length; i++) {
if (CheckArr[i] == true) {
db = new DataBase(getBaseContext());
Cursor dataC = db.selectQuery("SELECT path FROM Photos where name ='"+
currentFiles[i].getName() + "'");
Bitmap bitmap = decodeFile.decodeFile(new File(root + "/"+ currentFiles[i].getName()));
if (dataC.moveToFirst() && bitmap != null) {
FileOutputStream outputStream = new FileOutputStream(new
File(dataC.getString(dataC.getColumnIndex("path"))));
outputStream.write(decodeFile.getBitmapAsByteArray(bitmap));
outputStream.close();
File file = new File(root + "/" + currentFiles[i].getName());
file.delete();
} else {
if (bitmap == null) {
Log.v("YOUR TAG", "bitmap not found");
} else {}
Log.v("YOUR TAG", "unable to convert file");
}
dataC.close();
}
}
db.close();
inflateListView(currentFiles);
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
I'm not sure what you are doing on some things, but that's the direction I'd go in.

how to delete all check file using for loop?

This is my code which deletes only the first checked file.
I want to delete all checked files, what changed do I need to make?
How do I collect all values in CheckArr[i]?
The code only deletes the first checked file in grid. I want to first collect all checked values which are true then make database call(s).
boolean CheckArr[];
File[] currentFiles;
unhide.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for (int i = 0; i < CheckArr.length; i++) {
if (CheckArr[i] == true) {
db = new DataBase(getBaseContext());
try {
db.createDataBase();
} catch (IOException e1) {
e1.printStackTrace();
}
Cursor DataC = db
.selectQuery("SELECT path FROM Photos where name ='" +
currentFiles[i].getName() + "'");
if (DataC.getCount() > 0) {
Bitmap bitmap =
decodeFile.decodeFile(new File(root + "/" + currentFiles[i].getName()));
try {
FileOutputStream
outputStream = new FileOutputStream(
new File(DataC.getString(DataC
.getColumnIndex("path"))));
outputStream.write(decodeFile.getBitmapAsByteArray(bitmap));
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(root + "/" +
currentFiles[i].getName());
file.delete();
inflateListView(currentFiles);
}
DataC.close();
db.close();
}
}
You have to add a loop for the cursor DataC to delete all the files and not just the first one.
if (DataC.getCount() > 0) {
while (DataC.moveToNext()) {
//...
}
}

android download image and then read it from sd-card using sqlite

my question is that i have a code that is suppose to receive a variable that contains a website that has an image so this variable changes every time i send a new link this code should go online and download the image and save it to the sd-card then i read it and display it
so my problem with the code is if im sending 2 links to it, it downloads 1 of the images and it always stores it with the second image name (example: im sending image1 and image2 the code downloads image1 two times and stores it as "image2") when i mount the sd-card and check the image directory there is only 1 image there named image2, i thought that doInBackground was causing the problem but im also using onPostExecute() so please if someone can help me i would be thankful for his help Note this is how i call it:
Note: i have no errors in the code // no red marks
This is all the code:
private void UpdateAds(String Bookinfo,TextView myText){
elhgsdatabase db = new elhgsdatabase(this);
if (Bookinfo != "didn't read titels"){
String debContent="";
String output ="";
int NUMBEROFFIELDS = 5;
String s = addressString;
long idx;
String [] buffer = new String[NUMBEROFFIELDS];
output = "";
int l = 0;
while (s.indexOf("[")>-1){
int fk = s.indexOf("[");
int fl = s.indexOf("]");
if(fk > -1){
buffer[l] = s.substring(fk+1, fl);
s = s.substring(fl+1);
l++;
if (l == NUMBEROFFIELDS){
//1. Query the database to check if the book exists
//---get all titles---
db.open();
Cursor c = db.getBookTitle (buffer[0]);
if (c.getCount()==1)
{ myText.setText("This Books Exist \n"); }
else if(c.getCount()==0)
{ String locLink;
locLink = getLocalLink(buffer[3], buffer[0]);
c.moveToFirst();
if (!locLink.equalsIgnoreCase("-1")){
idx= db.insertTitle(buffer[0], buffer[1], buffer[2], getDate(buffer[3]), buffer[4], locLink);
}
else { //there was a problem with retrieval-saving of the Book info locally
myText.setText("There was a problem with retrieval-saving of the Book info locally\n");
}
}//if(c.getCount()==0)
else{//The table has two Books with the same Name. Do something
myText.setText("The table has two Books with the same Name\n");
}
c.close();
l = 0;
}//if(l == NUMBEROFFIELDS)
} //if (fk>-1)
}//while
db.close();
} //of if(BookInfo...
else {
myText.setText("Nothing is Done\n");
}
}
//This method gets the local link field of the active book records
// it goes on the web, gets the content and stores it in a place
// and saves the path of that place in the database for that
//it returns -1 if something wrong happened during the process
public String getLocalLink(String image_URL, String BookName){
/** This is what we do with this method:
* Go online, according to the link, get the content, call the method to save, get the local link
* and return it
*/
setContentView(R.layout.main);
reviewImageLink = image_URL;
URL reviewImageURL;
String name = reviewImageLink.substring(reviewImageLink.lastIndexOf("/") + 1);
try {
reviewImageURL = new URL(reviewImageLink);
if (!hasExternalStoragePublicPicture(name)) {
isImage = false;
new DownloadImageTask().execute(reviewImageURL);
Log.v("log_tag", "if");
isImage = true;
File sdImageMainDirectory = new File(Environment.getExternalStorageDirectory(), getResources()
.getString(R.string.directory));
sdImageMainDirectory.mkdirs();
File file = new File(sdImageMainDirectory, name);
Log.v("log_tag", "Directory created");
}
} catch (MalformedURLException e) {
Log.v(TAG, e.toString());
}
return ("/sdcard/Hanud/"+BookName+".jpg");
}
private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
// This class definition states that DownloadImageTask will take String
// parameters, publish Integer progress updates, and return a Bitmap
protected Bitmap doInBackground(URL... paths) {
URL url;
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);}
else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length- downloaded);
}
else {read = is.read(imageData, downloaded, buffersize);}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
protected void onPostExecute(Bitmap result) {
String name = reviewImageLink.substring(reviewImageLink
.lastIndexOf("/") + 1);
if (result != null) {
hasExternalStoragePublicPicture(name);
saveToSDCard(result, name);
isImage = true;
} else {
isImage = false;
}
}
}
public void saveToSDCard(Bitmap bitmap, String name) {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
mExternalStorageAvailable = mExternalStorageWriteable = true;
Log.v(TAG, "SD Card is available for read and write "
+ mExternalStorageAvailable + mExternalStorageWriteable);
saveFile(bitmap, name);
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
Log.v(TAG, "SD Card is available for read "
+ mExternalStorageAvailable);
} else {
mExternalStorageAvailable = mExternalStorageWriteable = false;
Log.v(TAG, "Please insert a SD Card to save your Video "
+ mExternalStorageAvailable + mExternalStorageWriteable);
}
}
private void saveFile(Bitmap bitmap, String name) {
String filename = name;
ContentValues values = new ContentValues();
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
sdImageMainDirectory.mkdirs();
File outputFile = new File(sdImageMainDirectory, filename);
values.put(MediaStore.MediaColumns.DATA, outputFile.toString());
values.put(MediaStore.MediaColumns.TITLE, filename);
values.put(MediaStore.MediaColumns.DATE_ADDED, System
.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
Uri uri = this.getContentResolver().insert(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
try {
OutputStream outStream = this.getContentResolver()
.openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean hasExternalStoragePublicPicture(String name) {
File sdImageMainDirectory = new File(Environment
.getExternalStorageDirectory(), getResources().getString(
R.string.directory));
File file = new File(sdImageMainDirectory, name);
if (file != null) {
file.delete();
}
return file.exists();
}
public void showAllBooks( )
{
final elhgsdatabase db = new elhgsdatabase(this);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Get new entry
db.open();
long currTime = System.currentTimeMillis();
String p_query = "select * from ads where timeFrom<=?";
Cursor c = db.rawQuery(p_query, new String[] { Long.toString(currTime)});
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
db.close();
}
}, 5000); // 5000 miliseconds
}
public long getDate(String s){
String[] formats = new String[] {
"yyyy-MM-dd HH:mm:ss"
};
SimpleDateFormat sdf=null;
String st;
for (String format : formats) {
sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("EST"));//UTC or EST
st = new String(sdf.format(new Date(0)));
System.err.format(format, st);
}
Calendar c = Calendar.getInstance();
Date dt;
try {
dt = sdf.parse(s);
c.setTime(dt);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return c.getTimeInMillis() ;
}
public void DisplayTitle(final Cursor c)
{
Toast.makeText(this,
"Title: " + c.getString(0) + "\n" +
"isbn: " + c.getString(1) + "\n" +
"Publisher: " + c.getString(2) + "\n" +
"Year: " + c.getString(3) + "\n" +
"Image On Line: " + c.getString(4) + "\n" +
"Image On SD " + c.getString(5) + "\n" ,
Toast.LENGTH_LONG).show();
String imageInSD = c.getString(5);
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
myImageView=(ImageView)findViewById(R.id.imageview1);
myImageView.setImageBitmap(bitmap);
}
----------
I'm pretty sure you're setting the second image name to the reviewImageLink (not sure if this is a class variable or what) variable. Instead, try passing both the URL and the String to the AsyncTask. Instead of passing a URL... pass in an Object... where the first one is the URL and the second is the name, and use that in the onPostExecute.
You don't show how ImageLink is set up. But as the filename is constructed from it, I guess your problem has almost nothing to do with the code you showed here.

Categories

Resources