how to delete all check file using for loop? - android

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()) {
//...
}
}

Related

Renaming file if exists in Android

I have been looking at the forum and found some tips but none of them bring me to the final solution. I need the code if possible, please.
I am creating a txt file every time I close my app and what I am aiming for is to rename the file in case it already exists with the following format:
file.txt - file(1).txt - file(2).txt
Up until now what I get is the following:
file.txt - file.txt1 - file.txt12
The code that I have is the following:
int num = 0;
public void createFile(String name) {
try {
String filename = name;
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++;
createFile(filename + (num));
}
} catch (IOException e) {
e.printStackTrace();
}
}
Thanks everybody in advance!
Your filename variable contains the whole name of your file (i.e. file.txt). So when you do this:
createFile(filename + (num));
It simply adds the number at the end of the file name.
You should do something like this:
int num = 0;
public void createFile(String prefix) {
try {
String filename = prefix + "(" + num + ").txt"; //create the correct filename
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if (!myFile.exists()) {
myFile.createNewFile();
} else {
num++; //increase the file index
createFile(prefix); //simply call this method again with the same prefix
}
} catch (IOException e) {
e.printStackTrace();
}
}
Then just call it like this:
createFile("file");

Broadcast Receiver using background process

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

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 can I backup sqlite file in SD Card programmatically?

When you use emulator your sqlite file is stored in a folder near your main application folder and you can download it. But this feature is not accessible in not rooted devices. How can I backup this existing sqlite file in SD Card programmatically?
I want to have a button in my application that stores this file in a special path in my SD Card. Is it possible?
Thanks,
You can try this, work for me, remember to get the WRITE_EXTERNAL_STORAGE permission in your manifest:
// Copy to sdcard for debug use
public static void copyDatabase(Context c, String DATABASE_NAME) {
String databasePath = c.getDatabasePath(DATABASE_NAME).getPath();
File f = new File(databasePath);
OutputStream myOutput = null;
InputStream myInput = null;
Log.d("testing", " testing db path " + databasePath);
Log.d("testing", " testing db exist " + f.exists());
if (f.exists()) {
try {
File directory = new File("/mnt/sdcard/DB_DEBUG");
if (!directory.exists())
directory.mkdir();
myOutput = new FileOutputStream(directory.getAbsolutePath()
+ "/" + DATABASE_NAME);
myInput = new FileInputStream(databasePath);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
} catch (Exception e) {
} finally {
try {
if (myOutput != null) {
myOutput.close();
myOutput = null;
}
if (myInput != null) {
myInput.close();
myInput = null;
}
} catch (Exception e) {
}
}
}
}
You can try following code,
String path = Environment.getExternalStorageDirectory().toString() + "/path";
File folder = new File( path );
if (!folder.exists())
{
folder.mkdirs();
}
File dbfile = new File( path + "/database.db" );
if ( !dbfile.exists() )
{
dbFile.createFile();
}
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
You can try this to copy a file:
public void copyFile(File in, File out) {
String DialogTitel = getString(R.string.daten_wait_titel);
String DialogText = getString(R.string.kopiervorgang_laeuft);
try {
// Dialogdefinition Prograssbar
final ProgressDialog dialog = new ProgressDialog(this) {
#Override
public boolean onSearchRequested() {
return false;
}
};
dialog.setCancelable(false);
dialog.setTitle(DialogTitel);
dialog.setIcon(R.drawable.icon);
dialog.setMessage(DialogText);
dialog.show();
new Thread(new MyCopyThread(in, out)) {
#Override
public void run() {
try {
FileChannel inChannel = new FileInputStream(
MyCopyThread.in).getChannel();
FileChannel outChannel = new FileOutputStream(
MyCopyThread.out).getChannel();
try {
System.out.println("KOPIEREN");
inChannel.transferTo(0, inChannel.size(),
outChannel);
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
setCopyError(false);
} catch (IOException e) {
setCopyError(true);
// throw e;
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
}
dialog.dismiss();
// Abschlussarbeiten
if (useExternalSD == true) {
// Externe DB
moveDBtoExternFinish();
} else {
// Interne DB
moveDBtoInternFinish();
}
moveDBFinishHandler.sendMessage(moveDBFinishHandler
.obtainMessage());
} catch (Exception ex) {
}
}
}.start();
} catch (Exception exx) {
}
}
This is the code to get the filname of your internal db:
File interneDB = getApplicationContext().getDatabasePath(MY_DB_NAME);
Replace MY_DB_NAME with the name of your DB

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