Android SQLite将数据从数据库获取到数组

时间:2012-02-10 11:26:11

标签: android sqlite

我想从光标中获取没有SimpleCursorAdapter部分的值。这是代码

public Cursor queueAll(){
  String[] columns = new String[]{KEY_ID, KEY_CONTENT1, KEY_CONTENT2,KEY_CONTENT3};
  Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
    null, null, null, null, null);
  return cursor;
 }

和活动方代码

cursor = mySQLiteAdapter.queueAll();

       from = new String[]{SQLiteAdapter.KEY_ID, SQLiteAdapter.KEY_CONTENT1, SQLiteAdapter.KEY_CONTENT2, SQLiteAdapter.KEY_CONTENT3};
       int[] to = new int[]{R.id.id, R.id.text1, R.id.text2,R.id.text3};
       cursorAdapter =
       new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
       listContent.setAdapter(cursorAdapter); 

       while(!cursor.isAfterLast())
       {
           String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
           String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
           if(tilt.equals("LEFT"))
           {
           Log.v("LEFT",pkg);
           }
           else if(tilt.equals("RIGHT"))
           {
               Log.v("RIGHT",pkg);
           }
           cursor.moveToNext();
       }

我得到的pkg值正确。但我想直接从光标获取值,同时删除SimpleCursorAdapter部分代码不起作用。 任何帮助将不胜感激:))

2 个答案:

答案 0 :(得分:0)

您可以在不声明适配器的情况下获取值。如果要在列表小部件中显示数据,则需要适配器。所以你可以如下:

cursor = mySQLiteAdapter.queueAll();

if (cursor == null) {
//check if there are errors or query just return null
}
if (cursor.moveToFirst()) {
       while(!cursor.isAfterLast())
       {
           String tilt = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT1));
           String pkg = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CONTENT3));
           if(tilt.equals("LEFT"))
           {
           Log.v("LEFT",pkg);
           }
           else if(tilt.equals("RIGHT"))
           {
               Log.v("RIGHT",pkg);
           }
           cursor.moveToNext();
       }
}

答案 1 :(得分:0)

首先,您必须计算表中有多少行。然后将该计数分配给变量,它用于创建数组。对于数组大小,您可以使用该count变量。然后创建一个for循环,并将该count变量用于回合。创建查询并为数组分配值之后。 100%有效!。

    int sqlcount;
    Cursor mFetch;

    SQLiteDatabase mydb = openOrCreateDatabase("your database name", MODE_PRIVATE, null);
    mydb.execSQL("create table if not exists customer(name varchar,email varchar)");
    Cursor mCount = mydb.rawQuery("select count(*) from customer", null);
    mCount.moveToFirst();
    sqlcount = mCount.getInt(0);
    mCount.close();

    String cname[] = new String[sqlcount];
    String cemail[] = new String[sqlcount];


     for(int i=0;i<sqlcount;i++) {

          mFetch= mydb.rawQuery("select name,email from customer", null);
          mFetch.moveToPosition(i);

          cname[i] = mFetch.getString(0);
          cemail[i] = mFetch.getString(1);


     }

     mFetch.close();

    Toast.makeText(MainActivity.this,String.valueOf(cname[0]),Toast.LENGTH_SHORT).show();
    Toast.makeText(MainActivity.this,String.valueOf(cemail[1]),Toast.LENGTH_SHORT).show();