Codename One:使用SQLite数据库连接并填充下拉菜单

时间:2016-03-14 11:32:28

标签: sqlite drop-down-menu codenameone

我正在尝试将SQLite数据库文件连接到选择器组件(接受字符串)。这应该类似于下拉菜单。我试图遵循以前的建议和例子,但没有成功。

如上一篇文章所述,我已将数据库文件保存在应用程序的源文件夹中。 View of the source folder where I have saved the database file (highlighted).

我用来实现我的应用程序的代码如下,以下布局。

// -----------------------

数据库代码

// -----------------------

public class MyApplication {

private Form current;
private Resources theme;

public void init(Object context) {
    theme = UIManager.initFirstTheme("/theme");

    // Pro only feature, uncomment if you have a pro subscription
    // Log.bindCrashProtection(true);
}

private Container Home() {
    Container home = new Container(new BoxLayout(BoxLayout.Y_AXIS));
    return home;
}

private Container AddItem() {
    Container addItem = new Container(new BoxLayout(BoxLayout.Y_AXIS));

    TextArea item = new TextArea("Add Item");
    addItem.addComponent(item);
    Picker selectItem = new Picker();
    selectItem.setType(Display.PICKER_TYPE_STRINGS);

//----------------------------------------------------------------------------------        

Database db = null;
Cursor cur = null;
try {
    db = Display.getInstance().openOrCreate("FoodAndBeverage.db");
    if(selectItem.getText().startsWith("Still Water")) {
        cur = db.executeQuery(selectItem.getText());
        int columns = cur.getColumnCount();
        addItem.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);
                addItem.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
            } else {
                addItem.add(BorderLayout.CENTER, "Query returned no results");
            }
        } else {
            addItem.add(BorderLayout.CENTER, "Query returned no results");
        }
    } else {
        db.execute(selectItem.getText());
        addItem.add(BorderLayout.CENTER, "Query completed successfully");
    }
    addItem.revalidate();
} catch(IOException err) {
    Log.e(err);
    addItem.removeAll();
    addItem.add(BorderLayout.CENTER, "Error: " + err);
    addItem.revalidate();
} finally {
    Util.cleanup(db);
    Util.cleanup(cur);
}

//---------------------------------------------------------------------------------------------

    addItem.addComponent(selectItem);
    TextField quantity = new TextField("", "Quantity (ml or g)", 4, TextArea.NUMERIC);
    addItem.addComponent(quantity);
    Button add = new Button("Add");
    addItem.addComponent(add);
    TextArea results = new TextArea("Results");
    addItem.addComponent(results);
    return addItem;
}

private Container Settings() {
    Container settings = new Container(new BoxLayout(BoxLayout.Y_AXIS));     
    TextArea nutrients = new TextArea("Target");
    settings.addComponent(nutrients);
    TextField volume = new TextField("", "Volume (ml)", 4, TextArea.NUMERIC);
    settings.addComponent(volume);
    TextArea duration = new TextArea("Hydration Duration");
    settings.addComponent(duration);
    settings.add("Start:");
    Picker start = new Picker();
    start.setType(Display.PICKER_TYPE_TIME);
    settings.addComponent(start);
    settings.add("End:");
    Picker end = new Picker();
    end.setType(Display.PICKER_TYPE_TIME);
    settings.addComponent(end);       
    Button save = new Button("Save");
    settings.addComponent(save);
    return settings;
}

public void start() {
    if(current != null)
    {
      current.show();
      return;
    }

    Form home = new Form("Hydrate", new BorderLayout());
    Tabs t = new Tabs();
    t.addTab("Home", Home());
    t.addTab("Intake", AddItem());
    t.addTab("Settings", Settings());
    home.add(BorderLayout.NORTH, t);
    home.show();

}

public void stop() {
    current = Display.getInstance().getCurrent();
}

public void destroy() {
}

}

因此,我非常感谢有关我出错的地方以及如何在我的代码中实施建议更改的任何建议和指导。

2 个答案:

答案 0 :(得分:0)

我假设src下的文件确实以扩展名db结束,因为Windows隐藏扩展无意义已打开。

此代码将 NOT 打开位于src中的数据库:

db = Display.getInstance().openOrCreate("FoodAndBeverage.db");

您需要执行以下操作,以便在第一次安装应用程序时隐式初始化数据库:

String path = Display.getInstance().getDatabasePath("FoodAndBeverage.db");
FileSystemStorage fs = FileSystemStorage.getInstance();
if(!fs.exists(path)) {
    try (InputStream is = Display.getInstance().getResourceAsStream(getClass(), "/FoodAndBeverage.db");
            OutputStream os = fs.openOutputStream(path)) {
        Util.copy(is, os);
    } catch(IOException err) {
            Log.e(err);
    }
}
db = Display.getInstance().openOrCreate("FoodAndBeverage.db"); 

请注意,上面的代码不会检查数据库的更新,因此假设数据库是只读的,您可能希望使用应用更新来更新/合并它。

答案 1 :(得分:0)

以上代码在Android设备上不起作用,这仅适用于模拟器。我在Android设备上多次测试过。在真正的Android设备中,根本没有加载数据库,显示 sql异常错误

  

“没有这样的表sql异常”。

看起来 preloaded sqlite .db 文件从未在真正的Android设备上进行过测试。