2013-08-31 129 views
0

我將顯示數據在sqlite數據庫中添加到微調器中。顯示很簡單,但我無法檢索到我添加到db的數據。這裏是我的代碼;從sqlite中檢索所有數據

public class MainActivity extends Activity { 

private Spinner spinner; 
private SQLiteDBOlustur sqlnesne; 
private SQLiteDatabase db; 
private ContentValues cv; 
private Cursor cursor; 
private ArrayList<String> arr; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    spinner = (Spinner) findViewById(R.id.spinnerIller); 
    arr = new ArrayList<String>(); 
    veriEkle(); 

    db = sqlnesne.getReadableDatabase(); 
    cursor = db.rawQuery("select * from iller", null); 

    if (cursor.moveToFirst()) { 
     do { 
      arr.add(cursor.getString(cursor.getColumnIndex("adsoyad"))); 
     } while (cursor.moveToPrevious()); 
    } 


    for (int i = 0; i < arr.size(); i++) { 
     System.out.println(arr.get(i)); 
    } 

} 

只有我能看到最後添加的數據。所以如何獲取我的sqlite數據庫中的所有數據?

另外這些都是添加數據的方法。

private void veriEkle() { 
    sqlnesne = new SQLiteDBOlustur(getApplicationContext()); 
    db = sqlnesne.getWritableDatabase(); 
    cv = new ContentValues(); 

     cv.put("il_adi", "Yalova"); 
    cv.put("il_adi", "Karabük"); 
    cv.put("il_adi", "Kilis"); 
    cv.put("il_adi", "Osmaniye"); 
    cv.put("il_adi", "Düzce"); 

    try { 
     db.insert("iller", null, cv); 
     Toast.makeText(getApplicationContext(), "Veriler eklendi!", 
       Toast.LENGTH_SHORT).show(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

回答

1

嘗試用cursor.moveToNext()更換cursor.moveToPrevious(),讓你通過遊標,而不是後撤步向前。

0
if (cursor != null && cursor.moveToFirst()) { 
     while (cursor.isAfterLast() == false) { 
      arr.add(cursor.getString(cursor.getColumnIndex("adsoyad"))); 
      cursor.moveToNext(); 
     } 
    } 
    cursor.close(); 

試試這種方式!

+0

這隻獲取最後添加的數據。 – emreturka

+0

我編輯我的問題。我添加一個方法,添加數據。 – emreturka

0

試試這個

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    spinner = (Spinner) findViewById(R.id.spinnerIller); 
    arr = new ArrayList<String>(); 

    veriEkle(); 

     String Table_Name="name of table"; 

     String selectQuery = "SELECT * FROM " + Table_Name; 
     SQLiteDatabase db = this.getReadableDatabase(); 

     Cursor cursor = db.rawQuery(selectQuery, null); 
     String[] data = null; 

     if (cursor.moveToFirst()) { 
      do { 
       // get the data into array,or class variable 
       // process your data here. 
      } while (cursor.moveToNext()); 
     } 
} 

希望它會幫助你。

+0

我一次又一次嘗試了這些代碼。但他們沒有工作。 – emreturka

+0

請發佈您的logcat。 – Andrain

+0

我正在添加81個數據,但它表示您已添加4個數據。 – emreturka