Bind the data in Spinner from Database in Android

Hi Friends,In this article i would like to share how to bind values in spinner from sqlite database in android.Spinner is nothing but just like a Dropdownlist..Now just follow the steps to bind the data

First,We need to write a Query in DBAdapter.class file to display the values in Spinner

This is the code for get all the values in spinner

// ---retrieves all Friend Names---

public Cursor getAllProjects() {

return db.query(DATABASE_TABLE_FRIEND, new String[] { FRIEND_ID, FRIEND_NAME,
}, null, null, null, null, null);
} 
Now,Create a new Xml file and save the file like MySpinner.xml

Next,open the file and write the Follwoing code in that

Next save that file and kept this folder in Layout folder

Next Create a class file and save the file like SpinnerClass.class

Next,Write the following code in that
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
Friendnames= (Spinner) findViewById(R.id.Friendnames);
BindValues(); 

}

public void BindValues()
{

try{
List list = new ArrayList();
DBAdapter db = new DBAdapter(getBaseContext());
db.open();
Cursor cursor = db.getAllProjectss();

if (cursor.moveToFirst()) {
do {
list.add(cursor.getString(1)); 
} while (cursor.moveToNext());
}

db.close();
FRND_NAME = (String []) list.toArray (new String [list.size ()]);
Log.v("PO's",String.valueOf(FRND_NAME.length));


ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_single_choice, FRND_NAME);
Friendnames.setAdapter(adapter);
}
catch(Exception e)
{
Log.v("Error","e.tostring()");

}

Finally save the file and run it

Thats it..

developercode
About the Author
Sayyad is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

Tanisha Sayyad

is a Software Engineer, Blogger and Founder of Developers Code from India.His articles mainly focus on .Net (Web and Windows based applications), Mobile Technologies (Android,IPhone,BlackBerry) and SEO.

2 comments:

 

Copyright @ 2013 Developers Code.

&