2013-05-16 102 views
0

有人可以教我如何從SQLite數據庫中獲取數據,並將從數據庫收集的所有信息放入微調器中。例如,我在我的數據庫中有一個tblState,我需要從數據庫中獲取所有State_name並將其提取到微調器。我將如何做到這一點?謝謝!將數據從數據庫插入到微控制器中android

回答

0

以下是使用sqlite的Android示例。這對初學者非常有用。示例包含ListActivity,而不是Spinner。只需正確學習示例,並且可以根據您的要求進行更改。

public class CRUDonDB extends ListActivity { 

    private final String SAMPLE_DB_NAME = "myFriendsDb"; 
    private final String SAMPLE_TABLE_NAME = "friends"; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 


     ArrayList<String> results = new ArrayList<String>(); 
     SQLiteDatabase sampleDB = null; 

     try { 
      sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null); 

      sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + 
        SAMPLE_TABLE_NAME + 
        " (LastName VARCHAR, FirstName VARCHAR," + 
        " Country VARCHAR, Age INT(3));"); 

      sampleDB.execSQL("INSERT INTO " + 
        SAMPLE_TABLE_NAME + 
        " Values ('Makam','Sai Geetha','India',25);"); 
      sampleDB.execSQL("INSERT INTO " + 
        SAMPLE_TABLE_NAME + 
        " Values ('Chittur','Raman','India',25);"); 
      sampleDB.execSQL("INSERT INTO " + 
        SAMPLE_TABLE_NAME + 
        " Values ('Solutions','Collabera','India',20);"); 

      Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM " + 
        SAMPLE_TABLE_NAME + 
        " where Age > 10 LIMIT 5", null); 

      if (c != null) { 
       if (c.moveToFirst()) { 
        do { 
         String firstName = c.getString(c.getColumnIndex("FirstName")); 
         int age = c.getInt(c.getColumnIndex("Age")); 
         results.add("" + firstName + ",Age: " + age); 
        }while (c.moveToNext()); 
       } 
      } 

      this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results)); 

     } catch (SQLiteException se) { 
      Log.e(getClass().getSimpleName(), "Could not create or Open the database"); 
     } finally { 
      if (sampleDB != null) 
       sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME); 
       sampleDB.close(); 
     } 
    } 
} 

也看看這個Spinner Example

+0

請不要在主線程上執行文件操作。 –

+0

@MaciejGórski,是的同意,但正如我所說這是初學者的例子。 – Lucifer

相關問題