Skip to content

Instantly share code, notes, and snippets.

@codenameone
Created March 2, 2016 13:22
Show Gist options
  • Save codenameone/282b02c20e7bd067f1f0 to your computer and use it in GitHub Desktop.
Save codenameone/282b02c20e7bd067f1f0 to your computer and use it in GitHub Desktop.
Sample for using SQLite in Codename One using the Database API. This sample presents a UI that allows querying the database and viewing the results in a table
Toolbar.setGlobalToolbar(true);
Style s = UIManager.getInstance().getComponentStyle("TitleCommand");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_QUERY_BUILDER, s);
Form hi = new Form("SQL Explorer", new BorderLayout());
hi.getToolbar().addCommandToRightBar("", icon, (e) -> {
TextArea query = new TextArea(3, 80);
Command ok = new Command("Execute");
Command cancel = new Command("Cancel");
if(Dialog.show("Query", query, ok, cancel) == ok) {
Database db = null;
Cursor cur = null;
try {
db = Display.getInstance().openOrCreate("MyDB.db");
if(query.getText().startsWith("select")) {
cur = db.executeQuery(query.getText());
int columns = cur.getColumnCount();
hi.removeAll();
if(columns > 0) {
boolean next = cur.next();
if(next) {
ArrayList<String[]> data = new ArrayList<>();
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
hi.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
} else {
hi.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
hi.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
db.execute(query.getText());
hi.add(BorderLayout.CENTER, "Query completed successfully");
}
hi.revalidate();
} catch(IOException err) {
Log.e(err);
hi.removeAll();
hi.add(BorderLayout.CENTER, "Error: " + err);
hi.revalidate();
} finally {
Util.cleanup(db);
Util.cleanup(cur);
}
}
});
hi.show();
@codenameone
Copy link
Author

Sample code for using SQLite and the Database API.

From the Codename One project

@blessingmobile
Copy link

This is quite a useful tool. Additionally to quickly setup I had to copy an existing sql lite database and paste it in the default .cn1/database folder:

https://github.com/codenameone/SQLSample/blob/master/src/MyDB.db

Initially the TextArea was not visible (on the default CN1 Blue theme), which meant I kept on pressing "execute" without knowing I have to type the Sql command. I think it will help adding the TextField UIID.

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