Where is stored the database retrieved by context.getDatabasePath("db1").getAbsolutePath() - android

I need to delete all the databases stored in the database space of the application. I stored them using this path: context.getDatabasePath("db1").getAbsolutePath()
I have a lot of databases, with random names, so i dont know al the names, i just want to delete all of them.
I tryed with this:
String filesDir = ApplicationContextProvider.getContext().getFilesDir().getAbsolutePath();
File cache = new File(filesDir);
if (cache.isDirectory()) {
String[] children = cache.list();
for (int i = 0; i < children.length; i++) {
System.out.println("Deleting: "+children[i]);
new File(cache, children[i]).delete();
}
}
But it doesn't works. The databases are still there.

You don't need to know that path. Just use the list of databases you can get to delete them.
for (String databaseName : context.databaseList()) {
context.deleteDatabase(databaseName);
}
If you really need it
File databasesPath = context.getDatabasePath("ignored").getParentFile();
The path you get via getFilesDir is a different one.

Related

Flutter - SQFlite store and load image from database

I want to save an image inside the sqflite database and the later on, I want to display it in a SliverAppBar as a background. Till now I am able to save the image(not sure if it is right, but throws no error XD):
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path;
File newImage = await _image.copy('$path/${recipeName.text}.png'); //_image already taken with image_picker plugin
String base64Encoded = base64Encode(newImage.readAsBytesSync());
And this String I am saving inside the database. But I also want to display. And as far I know, I have to get the String, but from now I on, I do not know anything how to get further. I have written a function to get the String, but do not know what I should do with this String. The function looks like this:
Future fetchRecipe(String name) async{
var dbHelper = new DBHelper();
Future<List<Recipes>> recipes = dbHelper.getSpecRecipe(name);
return recipes;
}
The getSpecRecipe(name) points to this function:
Future<List<Recipes>> getSpecRecipe(String recipeName) async{
List<Map> list = await _db.rawQuery("SELECT * FROM recipes WHERE name = ?", [recipeName]);
List<Recipes> recipes = new List();
for(int i =0; i < list.length; i++){
recipes.add(new Recipes(list[i]["id"], list[i]["name"], list[i]["definition"], list[i]["duration"], list[i]["favorite"], list[i]["timestamp"], list[i]["image"], list[i]["backgroundColor"]));
}
return recipes;
}
It would be awesome, if somebody would be able to solve my problem. Thanks in advanceXD
From the snippets provided, it seems that you're trying to save the image as a base64 on your database. And as mentioned by #Nordeast in the comments, it's better to save the image on the device's storage and store the file path instead. Also, given the snippets provided, it's difficult to replicate the behavior locally.

Restoring specific Sqlite Database to Android

I can back up and restore my most recent database OK but I want to save a time stamped Sqlite database like "back_up_12_11_17_13_32". This is so the user can restore not just the most recent back up but whatever back up he needs.
I'm wondering how to go about this?
Here's some pointers/techniques that I've utilised for what I believe is quite a flexible backup/restore facility.
I use the following to create the backup name.
private void setFullFilename() {
backupfullfilename.setText(
backupbasepart.getText().toString() +
backupdatetimepart.getText().toString() +
backupextension.getText().toString()
);
}
where
backupbasepart defaults to ShopWiseDB
backupdatetimepart defaults to the current time (when activity is started) in YYMMDDhhmm format as obtained via :-
Calendar cldr = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
return "_" + sdf.format(cldr.getTime());
backupextension defaults to .bkp
Noting that I allow all to be edited.
The App's backup/restore activity looks like :-
Note that the Spinner has been clicked to show the list of available backups and to also show how the timestamp is also converted to a more human readable format.
All backups are stored in PRIMARY PUBLIC EXTERNAL STORAGE (user has the option to copy/move to wherever) in the Download directory in a sub directory called ShopWise (this is fixed to simplify matters i.e. to not have to write a file explorer)
Using this directory also allows databases to be copied from other sources, so users could share databases if they so wished or this ability could be used for problem determination and resolution.
What backups shown in the Restore Spinner are determined by the 3 inputs that allows some flexibility - by default only standard backups are listed. However, blanking out the Base Filename will result in all files (well all that have an extension of .bkp (The File extension only shows files with that extension, blanking it out shows all extensions)).
e.g. if all are blanked out then all then you could have :-
When it boils down to it the core code for providing the list of restoreable files is :-
private void populateRestoreSpinner(Spinner spn,
TextView tv,
String basefilename,
String fileext,
StoreData sd,
TextView restorebutton) {
int fcount = 0;
ArrayList<File> reverseflist = new ArrayList<>();
//
sd = new StoreData(getResources().getString(R.string.backupdirectoryname),"xxx",true);
sd.refreshOtherFilesInDirectory();
// Build the File ArrayList
ArrayList<File> flst = new ArrayList<>(sd.getFilesInDirectory());
// Ascertain the relevant files that are needed for the restore backup
// file selector
for(int i = 0; i < flst.size(); i++) {
boolean endingok = flst.get(i).getName().endsWith(fileext);
boolean containsok = flst.get(i).getName().contains(basefilename);
if((strictbackupmode && endingok && containsok)
|| (!strictbackupmode && (endingok || containsok))) {
fcount++;
} else {
flst.remove(i);
i--;
}
}
// Reverse the order of the list so most recent backups appear first
// Also hide/show the Restore button and spinner according to if
// files exist or not
// (doing nothing in the case where the is no restore button i.e.
// null has been passed)
if(flst.size() > 0) {
for (int i = (flst.size() -1); i >= 0; i--) {
reverseflist.add(flst.get(i));
}
if (restorebutton != null) {
spn.setVisibility(View.VISIBLE);
restorebutton.setVisibility(View.VISIBLE);
}
} else {
if (restorebutton != null) {
spn.setVisibility(View.INVISIBLE);
restorebutton.setVisibility(View.INVISIBLE);
}
}
// Set the available count for display
//String bcnt = "Available Backups=" + Integer.toString(reverseflist.size());
tv.setText(Integer.toString(reverseflist.size()));
// Set the spinner adapter and dropdown layout and then set the
// spinner's adapter
AdapterFileList afl = new AdapterFileList(this,
R.layout.filelist,
reverseflist,
getIntent());
afl.setDropDownViewResource(R.layout.filelist);
spn.setAdapter(afl);
}
Note! StoreData is a glorified File/Directory listing that's pretty long winded but basically has members such as :-
private String directory;
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<>();

How to properly delete a database with Couchbase Lite Android?

I know that a Database object has a delete() method to delete a database.
But in the case where the database is corrupted (for instance), the opening of the database fails and consequently we don't have this Database object, which allows us to delete it (and then create a new empty one).
So, how is it possible to delete the database file if it is not possible to open this database?
I know that I could delete it manually doing something like:
Context context = ...;
String databaseName = ...;
Manager manager = new Manager(new AndroidContext(context), Manager.DEFAULT_OPTIONS);
File databaseDirectory = manager.getDirectory();
if (databaseDirectory != null) {
File databaseFile = new File(databaseDirectory, databaseName + ".cblite2"); // Or ".cblite"...
if (databaseFile.exists()) {
FileDirUtils.deleteRecursive(databaseFile);
}
}
But the fact I have to know the extension of the file is ugly for me...

How to insert a list of values in a column in excel sheet using aspose library in android?

I am using aspose.cell library in my android application to create excel sheets as an output in sdcard.
Here is my code:
void insertData() throws Exception {
//Get the SD card path
String sdPath = Environment.getExternalStorageDirectory().getPath() + File.separator;
Workbook wb = new Workbook();
Worksheet worksheet = wb.getWorksheets().get(0);
Cells cells = worksheet.getCells();
ArrayList<String> arr = new ArrayList<String>();
arr.add("one");
arr.add("two");
arr.add("three");
int i = 0;
for(String value : arr){
//Put some values into cells
//Log.i("rubanraj", value);
Cell cell = cells.get("A"+String.valueOf(++i)); //for A1,A2,A3...
cell.putValue(value);
}
wb.save(sdPath + "Cells_InsertRowsAndColumns.xlsx",SaveFormat.XLSX);
}
I have a set of data in arrayList, as final i need to insert that values in to a column in my worksheet. For that, i have used one for loop to get the cell position like A1,A2,A3.. from worksheet and inserting data one by one.
Everything is fine, but i havent used aspose lib before so i dont know much things. Actually what i required here is, how to insert the arraylist of values directly to a Column like (A,B,C...) in excel sheet using this aspose.cell lib?
Here I ll give some links which i referred for this work.
https://github.com/asposecells/Aspose_Cells_Android/blob/master/Examples/QuickStart/InsertRowsAndColumns/src/com/example/insertrowsandcolumns/MainActivity.java
https://github.com/asposecells/Aspose_Cells_Android
I have already tried apache POI and jxl libraries, but i am feeling aspose is easy to use compared to other libs.
Aspose.Cells provides some means and data import techniques which you may try. For example, you may directly try Cells.importArrayList() method to import your underlying ArrayList to the worksheet in Excel file, see the sample code here for your reference:
e.g
Sample code:
Workbook wb = new Workbook();
Worksheet worksheet = wb.getWorksheets().get(0);
Cells cells = worksheet.getCells();
ArrayList<String> arr = new ArrayList<String>();
arr.add("one");
arr.add("two");
arr.add("three");
//Importing the contents of ArrayList vertically (A1:A3).
cells.importArrayList(arr,0,0,true);
//Importing the contents of ArrayList horizontally (A10:C10).
cells.importArrayList(arr,9,0,false);
Please see the document for your complete reference.
I am Developer evangelist at Aspose.

Collections.sort between Directories and Files

I am using Arraylist of strings:
ArrayList entries = new ArrayList(Arrays.asList(""));
and giving values dynamically. It may contain the names of Directories or Files.
I need to show entries in ListView such that, first all directories are shown in sort order then files in sort order.
Is this possible? if yes, any hint? Appreciate the help.. I am using
Collections.sort(entries);
to sort my entries.
Use the 2 parameter version with a custom comparator. Compare it such that:
boolean firstFileIsDirectory = file1.isDirectory();
boolean secondFileIsDirectory = file2.isDirectory();
if(firstFileIsDirectory && !secondFileIsDirectory){
return -1;
}
if(!firstFileIsDirectory && secondFileIsDirectory){
return 1;
}
return String.compare(filename1, filename2);
I have done it. Logic used: separate the entries into two ArrayList. One having directories other files. Sort these two ArrayLists separately. Finally add these two to "entries". Here is the code:
private void sortEntries(String path){
ArrayList<String> entriesDir = new ArrayList<String>(Arrays.asList(""));
ArrayList<String> entriesFile = new ArrayList<String>(Arrays.asList(""));
entriesDir.removeAll(entriesDir);
entriesFile.removeAll(entriesFile);
int fileCounter=0, dirCounter=0;
path = path.equals("/") ? "" : path;
for(int i=1;i<=entries.size();i++){
if((new File(path+"/"+entries.get(i-1))).isFile()) entriesFile.add(fileCounter++, entries.get(i-1));
else entriesDir.add(dirCounter++, entries.get(i-1));
}
Collections.sort(entriesDir,String.CASE_INSENSITIVE_ORDER);
Collections.sort(entriesFile,String.CASE_INSENSITIVE_ORDER);
entries.removeAll(entries);
entries.addAll(entriesDir);
entries.addAll(entriesFile);
}

Categories

Resources