listview(2、CursorAdapter)

CursorAdapter 适配器主要用以从数据库读取例子的场景,例子如下:

1. 定义一个adapter,继承CursorAdapter

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例子。

 

你可能感兴趣的:(ListView)