2016-11-26 17 views
0

ListViewに、自分のデータベーステーブルのデータを取り込みました。ListViewからデータを抽出する

選択したアイテムからデータを取得するにはどうすればよいですか?

これは私がListViewコントロールを移入する方法である:

SimpleCursorAdapter SimpleCursorAdapter; 
ListView listCategories = (ListView) findViewById(R.id.categoryList); 
categoryRepo categoryRepo = new categoryRepo(this); 
TextView textview= (TextView) findViewById(R.id.textView); 

private void displayCategories() 
{ 
    Cursor cursor = categoryRepo.getCategories(); 

    if (cursor == null) 
    { 
     textview.setText("Error"); 
     return; 
    } 
    if (cursor.getCount() == 0) 
    { 
     textview.setText("No categories."); 
     return; 
    } 

    String[] from = new String[] {category.KEY_CATEGORY_NAME}; 
    int[] to = new int[] {android.R.id.text1}; 

    SimpleCursorAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,from,to,0); 
    listCategories.setAdapter(SimpleCursorAdapter); 

} 

は私がlistCategories.setOnItemClickListenerを使用することによって、これを行うことができることを知って、私は方法がわかりません。ご協力ありがとうございます。

CATEGORY_NAMEの値を取得します。

答えて

1
listCategories.setOnItemClickListener(new OnItemClickListener(){ 
    @Override 
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, 
      long arg3) { 
     // TODO Auto-generated method stub 

     Cursor cursor = (Cursor) SimpleCursorAdapter.getItem(position); 
    } 
}); 

How to get string from selected item of SimpleCursorAdapter?

+0

しかし、このデータを文字列で取得するにはどうすればよいですか? 気にしないで、私はそれを理解しました。ありがとうございました!それは私が予想したよりもうまくいく。 (cursor.getString(cursor.getColumnIndex(category.KEY_ID))) – ktos1234

+0

これはうまくいきますが、OnItemClickメソッドのパラメータが何を意味するのかを私に説明してもらえますか?私はarg0、arg1、arg3を意味しますか? – ktos1234

+1

https://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html –

1

このお試しください:java.lang.ClassCastExceptionが::私はこのエラーを得た

listCategories.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { 
      Cursor cursor = (Cursor) adapterView.getItemAtPosition(position); 
      if (cursor.moveToFirst()){ 
       String selectedValue = cursor.getString(cursor.getColumnIndex(category.KEY_CATEGORY_NAME)); 
       // do what ever you want here 
      } 
      cursor.close(); 
     } 
    }); 
+0

をandroid.database.sqlite.SQLiteCursor java.lang.Stringで – ktos1234

+0

編集にキャストすることはできません、見てください – rhari

関連する問題