开发者

Binding data from a Cursor to a Spinner Android

I am trying to populate a Spinner in an A开发者_如何学Cndroid dialog. When the user clicks a button, a dialog pops up and I load the layout from an XML file. Now I am trying to populate that Spinner from a SQL query. I have searched all over and cannot figure out what the problem is. I can loop through the Cursor and add each value to an ArrayAdapter and then use that as the list for the spinner but that doesn't come with the _id's from the database. I have done this before using a SimpleCursorAdapter and I have even copied and pasted my old code exactly and still it isn't working. Any help would be much appreciated.

My Dialog code:

private void displayNewInteractionDialog() {
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.mm_new_dialog);
        dialog.setTitle(R.string.mm_new_dialog_title);
        dialog.setCancelable(true);

        final Spinner spinner = (Spinner) dialog.findViewById(R.id.mm_spinner);

        DatabaseInterface db = new DatabaseInterface(this);
        db.open();

        Cursor c = db.getNames();

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
            android.R.layout.simple_spinner_item,
            c,
            new String[] {DatabaseInterface.KEY_ID, DatabaseInterface.KEY_NAME}, 
            new int[] {android.R.id.text1});

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);

        c.close();
        db.close();

        dialog.show();
}

Here is the code that returns a Cursor in my DatabaseInterface class:

public Cursor getNames() {
        return db.query(DATABASE_TABLE_4, new String[] {DatabaseInterface.KEY_ID, DatabaseInterface.KEY_NAME}, null, null, null, null, null);
    }

I know this will work I am just missing something apparently. I know that I could load the Spinner with the list of names from the ArrayAdapter that I stated above and also populate an array with the ID's from the query and when the user selects an item I could just grab the corresponding one from the array of ID's... But I know the SimpleCursorAdapter will work I just can't seem to figure it out and I'm not giving up until I do haha. Thanks in advance for any help.


Well looks like I am dumb haha... For some reason or another, probably from just trying numerous things and then forgetting to remove parts that I had added. I just removed c.close(); and now everything is fine. I remember adding that as I was trying to figure things out and I must've fixed the problem somewhere else and then didn't realize it because this line was still in there. Since I am not actually doing anything with the Cursor other than passing it to a function, it doesn't need to be closed. Anyhow all is good, I knew it was going to be something stupid. Like usual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜