How to delete all the boxes in Hive Flutter? - flutter

I am developing an application using Flutter; it will store some data locally, so I decided to use Hive package which was really amazing package to store data. So now I will store all the data locally when the user press the sync button. After that, if the user clicks sync again, I have to delete all the boxes and store data which may or may not have the same box name.
I don't want to increase the application storage to increase if the sync button is clicked, I want to delete all the boxes and again I want to create the box.

You can use deleteFromDisk method. It removes the file which contains the box and closes the box.
_myCourseBox.deleteFromDisk();

Unfortunately, I don't think a feature to clear() all (opened, plus unopened) Hive boxes has been implemented. The box files are basically thrown into your device's application document directory as *.hive files (with compacted files as *.hivec and lock files as *.lock). There's no separate key-value store (or Hive box) that keeps track of previously created boxes, though you can implement such a Hive box yourself and iterate over those values as you please.
In your case, where you simply want to delete all the boxes in one sweep, a workaround could be to place all Hive boxes into a sub-directory (using Hive.initFlutter('chosenPath') ) and simply delete the directory when necessary using standard file operations. The only gotcha being that you call Hive.close() to close all open boxes before attempting this (to delete the undeletable *.lock files).
To simplify cross-platform references to the app's document directory you can use the path_provider package. Add path_provider: ^1.6.5 to your dependencies in pubspec.yaml, and where necessary in your dart application import 'package:path_provider/path_provider.dart'; and import 'dart:io'; for file operations;
Let's say you use Hive.initFlutter('chosenPath') to initialise and store your Hive.
So whenever you want to clear all boxes (after ensuring Hive.close() has been called), you could use the following code:
// Get the application's document directory
var appDir = await getApplicationDocumentsDirectory();
// Get the chosen sub-directory for Hive files
var hiveDb = Directory('${appDir.path}/chosenPath');
// Delete the Hive directory and all its files
hiveDb.delete(recursive: true);
The directory will be re-generated from scratch the next time you call Hive.initFlutter('chosenPath').

You didn't share any code so I will just give an example.
I would suggest you to open the boxes in your main function
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Hive.initFlutter();
Hive.registerAdapter(yourAdapter());
await Hive.openBox('yourBoxName');
}
When user wants to sync, you can do following;
// It will delete all the entry in the box
Hive.box('yourBoxName').clear();
yourSyncOperation();

Related

Update sepcific line in file

Hi is there a method from which I can update a specific line in a file.
My file has data seperated by line break
Sample example to delete line but I have to write everything into file again, can I perform CRUD opertion directly on file lines ?
I want to update specific line in file wihout reading entire file => update string and => write all lines to file.
I may switch to any kind of file type that can offer me this functionality.
Is there a way to store data in row column architecture like sql ?
import 'dart:io';
Future<void> myAsyncFunction() async {
const index = 5;
final File f = File('test.txt');
final List<String> lines = await f.readAsLines();
lines.removeAt(index);
await f.writeAsString(lines.join('\n'));
}
This should be possible by using the String Scanner library, it provides a class called LineScanner and LineScannerState through which you can set the position.
I have not tried this for the exact use case you mention above, so please do evaluate it for your use-case
Files are stored as a contiguous array of bytes on a disk, there is no way to remove a specific line without scanning for newlines and shifting trailing data to fill the void.
For a more sophisticated way of storing data there are many popular database packages, including sqflite, hive, drift, sembast, and objectbox.

How to avoid opening a QuickInput when choosing files to compare in a vscode extension?

In my case I want to compare two files.
But I don't want the user to select the File in the QuickInput form, i want to choose this directly for him.
vscode.commands.executeCommand("workbench.files.action.compareFileWith", filePath)
This results in
Meaning that filePath is ignored and a QuickInput is displayed instead.
Is there a way to directly select a file programmatically instead of showing the QuickInput first?
While the compareFileWith command probably requires a QuickInput panel to use, you can use the other compare commands to do what you want:
// using the current file for the 'compareWith' file
const currentFileUri = vscode.window.activeTextEditor.document.uri;
// create a Uri from some filePath
const compareWithSelectedUri = vscode.Uri.file('C:\\Users\\Mark\\OneDrive\\Test Bed\\BAR.txt');
await vscode.commands.executeCommand('selectForCompare', currentFileUri)
await vscode.commands.executeCommand('compareFiles', compareWithSelectedUri);
This works in my testing.
Looking at compareFileWith in https://github.com/microsoft/vscode/blob/9b9361cfd1b0678f0bb0b32bf9925b6520bb9926/src/vs/workbench/contrib/files/browser/fileActions.ts I don't think there is any way to avoid the QuickInput opening.
Alternatively, what you are asking for would be "easy" if an open method were supported on TabGroups api like the close methods. You would create a tab of kind TabInputTextDiff with an original uri and a modifieed uri.
When the TabGroups api was being developed there was an open tab method but it was removed prior to release and hasn't seen any love since. See https://github.com/microsoft/vscode/commit/aa69f3d7623c464aba726d12ea0d83428f43e8b9#commitcomment-71831337.
I'll open an issue to see if it will help (and post the link here later).

How to get a list of all cached audio?

For example, my podcast app has a list of all downloaded podcast, how do I get a list of all LockCachingAudioSource that has been downloaded using request() method?
When you create your LockCachingAudioSource instances, you can choose the location where you want them to be saved. If you create a directory for that purpose, you can obtain a directory listing using Dart's file I/O API. The directory listing will also show partially downloaded files and other temporary files, which you want to ignore. These have extensions .mime and .part.
Having explained that, here is a solution. First, create your cache directory during app init:
final cacheDir = File('/your/choice/of/location');
...
await cacheDir.create(recursive: true);
Then for each audio source, create it like this:
import 'package:path/path.dart' as p;
...
source = LockCachingAudioSource(
uri,
cacheFile: File(p.joinAll([cacheDir, 'yourChoiceOfName.mp3'],
);
Now you can get a list of downloaded files at any time by listing the cacheDir and ignoring any temporary files:
final downloadedFiles = (await _getCacheDir()).list().where((f) =>
!['mime', 'part'].contains(f.path.replaceAll(RegExp(r'^.*\.'), '')));
If you need to turn these files back into the original URI, you could either create your own database to store which file is for which URI, or you choose the file name of each of your cache files by encoding the URI in base64 or something that's reversable, so given a file name, you can then decode it back into the original URI.

VSCode Extension: Add document metadata when opening file

I am building an extension that will open files from a remote server, but need to add some metadata into each document opened, which I will use later when the document is saved/closed.
Is there a way I can insert metadata into each document?
vscode.workspace.openTextDocument(filePath + fileName).then(doc => {
// Add some document specific metadata
vscode.window.showTextDocument(doc);
});
I understand that VSC does that, for example storing the caret and scroll positions, or selection if any, and so on, retrieving it when you reopen the file.
I believe it does that by storing data outside of the files, otherwise it would alter their data, or it would need to manipulate metadata according to the local system (Windows, macOS, Linux, etc.), which is not obvious, if even possible.
On Windows, in C:\Users<user name>\AppData\Roaming\Code, there are a number of databases which might fit this purpose, you can do a similar thing.

TYPO3 - Extbase - Detect missing files for a given FileReference

I've tried three different ways to detect if a FileReference's original file is still existing (i.e. file has been deleted outside TYPO3 using SFTP or similar):
if($fileReference instanceof \TYPO3\CMS\Extbase\Domain\Model\FileReference) {
$isMissing = $fileReference->getOriginalResource()->getStorage()->getFile($fileReference->getOriginalResource()->getIdentifier())->isMissing();
$isMissing = $fileReference->getOriginalResource()->getOriginalFile()->isMissing();
$isMissing = $fileReference->getOriginalResource()->isMissing();
}
Only the first one give me the right isMissing() value.
The property isMissing is an database value, which is set if the storage detect an missing file. On getFile the storage check if the file is missing and set "isMissing" for the file. If you dont persist this to the database, the setting is get loose with the next call.
You can also call $isMissing = $fileReference->getOriginalResource()->getStorage()->hasFile($fileReference->getOriginalResource()->getIdentifier());
You can run the file indexer scheduler (TYPO3\CMS\Scheduler\Task\FileStorageIndexingTask) if you want to check frequently for deleted files. This should be required if you let change files externaly (like ftp).