Wednesday, May 18, 2011

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.

Labels: , , , , , ,

2 Comments:

At June 18, 2011 at 12:51 PM , Anonymous Anonymous said...

Its very Simple Thanks .....

 
At June 18, 2011 at 12:51 PM , Anonymous Anonymous said...

Gr8...

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home