2011年11月30日

Android 讀取資料庫(SQLite)的下拉式選單(Spinner)

DbHelper.java
 
public class DbHelper extends SQLiteOpenHelper {
 private static final String DATABASE_NAME = "xxxx.sqlite"; //資料庫名稱
 private static final int DATABASE_VERSION = 1; //資料庫版本
 private static final String table_name = "table";
 private SQLiteDatabase db;
 
 public DbHelper(Context context) { //建構子
  super(context, DATABASE_NAME, null, DATABASE_VERSION);
  db = this.getWritableDatabase();
 }
 
 @Override
 public void onCreate(SQLiteDatabase db) { //初始化資料庫 
  DATABASE_CREATE_TABLE =
       "create table class1 ("
           + "_id INTEGER PRIMARY KEY AUTOINCREMENT,"
           + "class_name TEXT"
       + ");";
  db.execSQL(DATABASE_CREATE_TABLE);
  String TABLE_Insert = 
    "INSERT INTO class1 (class_name) VALUES ('食');";
  db.execSQL(TABLE_Insert);
  TABLE_Insert = 
    "INSERT INTO class1 (class_name) VALUES ('衣');";

  db.execSQL(TABLE_Insert);
 }

public Cursor getclass1(){  //取得class1資料表內容
  return db.query("class1",new String[] {"_id","class_name"} , null, null, null, null, null);
 }

MainActivity.java

public class MainActivity extends Activity {
 private DbHelper dbHelper; 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.firstlayout);
        Spinner sp01 = (Spinner)findViewById(R.id.spinner01);
        dbHelper = new DbHelper(this);
        final Cursor cursor = dbHelper.getclass1();
         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item ,cursor, new String[] { "class_name" }, new int[] {android.R.id.text1});
         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         sp01.setAdapter(adapter);

          //.....處理點選後行為....

 }

}

3 意見:

匿名 提到...

At this time I am ready to do my breakfast, afterward having my breakfast coming yet again to read other news.


Feel free to visit my website ... http://zorporno.com

匿名 提到...

Hi. I wanted to drop you a fast word to precise my thanks.
Ive been following your blog for a month or so and have picked up a ton of good data and enjoyed the method youve structured your site.
I am making an attempt to run my very personal blog nonetheless I feel its too basic and
I must concentrate on a number of smaller topics. Being all issues to all folks just
isn't all that its cracked up to be

Look into my homepage tips to get pregnant

匿名 提到...

Probably the most crucial approach in the P90 X Nutrition Plan there order of
p90x ab ripper is still an ongoing debate over the safety of these.

When You Have order of p90x ab ripper To Skip A DayFirst of
all, since This Program EXACTLY! If you have an early morning race or
workout, it's best regularly can actually use an extra dose of it every day. It is designed to get you used bodies need different things.

Feel free to surf to my blog additional reading

張貼留言

##EasyReadMore##