2012-04-16 20 views
1

SQLiteクエリはCursorを返します。 Cursorに余分な行を追加するには、MatrixCursor(クリックすると実際のデータの最初の項目が自動的に選択されないようにする)を実装します。次に、それらをSimpleCursorAdapterにマップしたいと思います。私はポスト(とコード)を読んだが、以下のリストにある私のコードにそれをコード化する方法はまだ分かりません。SpinnerのMatrixCursorを実装するにはどうすればよいですか?

Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, whereClause, 
      whereArgs, null, null, null, null); 

    // Create Spinner View object from layout resource 
    Spinner spinner = (Spinner) findViewById(R.id.spinner); 

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_spinner_item, // Use a template 
                // that displays a 
                // text view 
      cursor, // Give the cursor to the adapter 
      new String[] {"ename"}, // Map the NAME column in the 
               // people database to... 
      new int[] {android.R.id.text1}); 

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(adapter); 
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); 

答えて

5

あなたは、単純なCursorからMatrixCursorを構築したい場合は、全体の初期Cursorを解析して、必要な行追加する必要があります:あなただけにこれをやっている場合は

//... 
    MatrixCursor mc = new MatrixCursor(resultColumns); 
    // add extra rows, this will probably not work if you want to insert them 
    // between the initial cursor rows because of the _id column that need autoincrement values 
    mc.addRow(new Object[] { new Long(-2), "Extra name1" }); 
    mc.addRow(new Object[] { new Long(-1), "Extra name2" }); 
    // I don't know what your cursor holds, I assumed you have the _id column(long value) 
    // and a name(String value) 
    int size = cursor.getCount(); 
    for (int i = 0; i < size; i++) { 
     cursor.moveToPosition(i); 
      mc.addRow(new Object[] { 
      cursor.getLong(cursor.getColumnIndex(/*the _id column*/)), 
      cursor.getString(cursor.getColumnIndex(/* the name column(ename?!?)*/)) }); 
    } 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_spinner_item, mc, new String[] {"ename"}, new int[] {android.R.id.text1}); 
//... 

Spinnerが表示されているときにOnItemSelectedListenerが発砲しないようにしてください。多分別の方法があります。たとえば、リスナーの場合:

//boolean status = true; flag in MyOnItemSelectedListener 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, 
      int position, long id) { 
     if (status) { 
      status = false;// this is the first listener trigger so you probably want to ignore it 
      return; 
     } 
     // do stuff here 
    } 

注:私は上記の解決策がどれほど優れているかわかりません。あなたが見ている場合は、このSpinner関連の問題におそらくもっと良い解決策があります。

+0

大変ありがとうございます – j2me

+0

'new Long(-2)'の代わりに 'Long.valueOf(-2)'を使用してください。 – bancer

関連する問題