从sqlite中检索所有数据

时间:2013-08-31 01:34:18

标签: android sqlite

我将在sqlite db中显示数据到spinner。显示很简单但我无法检索我添加到db.Here的数据是我的代码;

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();
    }
}

3 个答案:

答案 0 :(得分:1)

尝试将cursor.moveToPrevious()替换为cursor.moveToNext(),以便您向前走过光标而不是向前。

答案 1 :(得分:0)

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

试试这个!!

答案 2 :(得分: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());
        }
}

希望它会对你有所帮助。