2012年3月10日 星期六

[TQC+ Android] 2-9 姓名清單 Use ArrayAdapter , Spinner , SQLiteDatabase





將string.xml裡的陣列資料寫入資料庫 , 再從資料庫裡依字母排序出來 , 並放在Spinner裡 ,  下面是程式碼。





package COM.TQC.GDD02;


import android.app.Activity;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class GDD02 extends Activity
{
 private static final String DBNAME = "MY_DB";
 private static final String TABLENAME = "MY_TABLE";
 private static final String FIELD01_NAME = "_id";
 private static final String FIELD02_NAME = "_text1";
 private SQLiteDatabase dataBase;
 private Spinner Spinner01;
 private String[] strNames , orderNames;
 private Cursor cursor;
 //資料筆數
 private int recordCount;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
     super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Spinner01 = (Spinner) findViewById(R.id.Spinner01); 
        Resources resources = getResources(); 
        strNames = resources.getStringArray(R.array.strNames);
               
        String CREATE_SQL = "create table if not exists "+TABLENAME+" ("+FIELD01_NAME+" INTEGER PRIMARY KEY, "+FIELD02_NAME+" TEXT)";
        dataBase = openOrCreateDatabase(DBNAME, MODE_PRIVATE, null);
        dataBase.execSQL(CREATE_SQL);
     
     for(int i=0; i0)
     {
      cursor.moveToFirst();
      orderNames = new String[strNames.length];
      for(int i=0; i < strNames.length ; i++)
      {
       orderNames[i] = cursor.getString(1);
       cursor.moveToNext();
      }
     }
     
     ArrayAdapter adapter = new ArrayAdapter(this,  
                android.R.layout.simple_spinner_item, orderNames);  
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
        Spinner01.setAdapter(adapter);      
        Spinner01.setSelection(0);
        dataBase.execSQL("DROP TABLE "+TABLENAME);
        dataBase.close();
    }
}



main.xml
 
 





資料來源 , values/strings.xml
    
    姓名清單
 
  Ella
  Body
  David
  Andy
  Cindy
  GiGi
  Fancy
 





P.S. 題目中所要求的Variable和Method皆會保留 , 也會根據題目所要求的流程去實作 , 縱使題目要求繞遠路....



沒有留言:

張貼留言

Google Analytics