Skip to content

Instantly share code, notes, and snippets.

@codenameone
Last active July 8, 2020 09:57
Show Gist options
  • Save codenameone/a941ef1f2f398b2c1074 to your computer and use it in GitHub Desktop.
Save codenameone/a941ef1f2f398b2c1074 to your computer and use it in GitHub Desktop.
A simple Storage manager demo listing the files within the Codename One storage and allowing us to add/view/remove them.
public void showForm() {
Toolbar.setGlobalToolbar(true);
Form hi = new Form("Storage", new BoxLayout(BoxLayout.Y_AXIS));
hi.getToolbar().addCommandToRightBar("+", null, (e) -> {
TextField tf = new TextField("", "File Name", 20, TextField.ANY);
TextArea body = new TextArea(5, 20);
body.setHint("File Body");
Command ok = new Command("OK");
Command cancel = new Command("Cancel");
Command result = Dialog.show("File Name", BorderLayout.north(tf).add(BorderLayout.CENTER, body), ok, cancel);
if(ok == result) {
try(OutputStream os = Storage.getInstance().createOutputStream(tf.getText())) {
os.write(body.getText().getBytes("UTF-8"));
createFileEntry(hi, tf.getText());
hi.getContentPane().animateLayout(250);
} catch(IOException err) {
Log.e(err);
}
}
});
for(String file : Storage.getInstance().listEntries()) {
createFileEntry(hi, file);
}
hi.show();
}
private void createFileEntry(Form hi, String file) {
Label fileField = new Label(file);
Button delete = new Button();
Button view = new Button();
FontImage.setMaterialIcon(delete, FontImage.MATERIAL_DELETE);
FontImage.setMaterialIcon(view, FontImage.MATERIAL_OPEN_IN_NEW);
Container content = BorderLayout.center(fileField);
int size = Storage.getInstance().entrySize(file);
content.add(BorderLayout.EAST, BoxLayout.encloseX(new Label(size + "bytes"), delete, view));
delete.addActionListener((e) -> {
Storage.getInstance().deleteStorageFile(file);
content.setY(hi.getWidth());
hi.getContentPane().animateUnlayoutAndWait(150, 255);
hi.removeComponent(content);
hi.getContentPane().animateLayout(150);
});
view.addActionListener((e) -> {
try(InputStream is = Storage.getInstance().createInputStream(file)) {
String s = Util.readToString(is, "UTF-8");
Dialog.show(file, s, "OK", null);
} catch(IOException err) {
Log.e(err);
}
});
hi.add(content);
}
@codenameone
Copy link
Author

Sample usage of the Storage class.

From the Codename One project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment