listview(2、CursorAdapter)

5423 ワード

CursorAdapterアダプタは、主にデータベースから例のシーンを読み込むために使用されます.例は次のとおりです.
1.CursorAdapterを継承するadapterを定義する
public class Adapter2 extends CursorAdapter {



    private int resourceid;

    private LayoutInflater mInflater = null;

    private TextView  title;

    private TextView  content;

    private ImageView image;

    

    public Adapter2(Context context, Cursor c, int id) {

        super(context, c, id);

        resourceid = id;

    }



    @Override

    public View newView(Context context, Cursor arg1, ViewGroup arg2) {

        mInflater = (LayoutInflater) context  

                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = mInflater.inflate(resourceid, null);

        image   = (ImageView) view.findViewById(R.id.image);    

        title   = (TextView) view.findViewById(R.id.title);    

        content = (TextView) view.findViewById(R.id.content); 

                

        return view;

    }



    @Override

    public void bindView(View arg0, Context arg1, Cursor cursor) {

        image.setImageResource(R.drawable.ic_launcher);

        title.setText(cursor

                .getString(cursor.getColumnIndex("title")));

        content.setText(cursor

                .getString(cursor.getColumnIndex("content")));

    }



}

2.activityでテストデータを初期化し、このアダプタを関連付けます.
public class MainActivity extends ListActivity {



    private SQLiteDatabase db;

    private final static String DB_NAME = "infos";

    

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);        

        

        initTestData();

        Cursor cursor = db.rawQuery("SELECT * FROM info", null);

        Adapter2 adapter = new Adapter2(this.getApplicationContext(), cursor,R.layout.item_list);

        this.setListAdapter(adapter);

        

        

    }

    

    public void initTestData(){

        db = openOrCreateDatabase(DB_NAME, this.MODE_PRIVATE, null);  

        db.execSQL("DROP TABLE IF EXISTS info");    

        db.execSQL("CREATE TABLE IF NOT EXISTS info (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR, content VARCHAR)");

        

        db.execSQL("INSERT INTO info VALUES (NULL,' A',' ')"); 

        db.execSQL("INSERT INTO info VALUES (NULL,' B',' ')");

        db.execSQL("INSERT INTO info VALUES (NULL,' C',' ')");

        db.execSQL("INSERT INTO info VALUES (NULL,' D',' ')");

        db.execSQL("INSERT INTO info VALUES (NULL,' E',' ')");

    }

}

メモ:layoutファイルはbaseAdapterの例と同じです.