Skip to content Skip to sidebar Skip to footer

Is It Possible To Load A Dropdown Box In Android With Items From A Sqlite Table? How?

I'm recoding an application for the Android platform. I'd like to have a dropdown box populated with items in a user editable table. Is this 'easily done' in Android?

Solution 1:

yes,it is easily done by using spinner.

try following code

  int i=0;
        Spinner sp1=(Spinner)findViewById(R.id.spinner1);
        Dbhelper db1=newDbhelper(this);
        SQLiteDatabase db=db1.getReadableDatabase();
        Cursor c1=db.rawQuery("select accNo from Account4 where bankName='"+str+"'",null);
        acc=newString[c1.getCount()];

        while(c1.moveToNext()){
        acc[i]=c1.getString(c1.getColumnIndex("accNo"));
        i++;
       }


         ArrayAdapter<String> adp=newArrayAdapter<String(this,android.R.layout.simple_spinner_dropdown_item,acc);

            sp1.setAdapter(adp);
             c1.close();
             db.close();    

Solution 2:

First of all, I suggest you use the LoaderManager and Loader in order to operate with your database. If you just use the straightforward approach as suggested by user3355820, you will face terrible consequences with your application lifecycle (cursor leak and subsequent ineffective queries to your database on Activity recreation are the lesser of possible vile things).

So, first of all, read Life before Loaders Pt.1 - there are three parts of this article in this awesome blog, and I suggest you read all of them. It will help you understand the conception of Loader and what you should not do.

Then, read CursorLoader without ContentProvider. This will help you to build your own Loader without some excessive (in your usecase) things like ContentProvider.

To populate your dropbox with user data, just wrap the results of your custom CursorLoader in simple SpinnerAdapter implementation, set your Spinner adapter to your adapter implementation and you're all chocolate :)

And finally finally :), if you'd like some dirty code examples, you can take a look at my github repo, it contains some basic implementation of the pattern I introduced to you above (this is pending project, and things are not yet finished, but basic CRUD works).

Post a Comment for "Is It Possible To Load A Dropdown Box In Android With Items From A Sqlite Table? How?"