ListView显示数据库的数据-SimpleCursorAdapter的使用

1.新建dbhytcs项目
这里写图片描述

2.HytcSQLiteOpenHelper.java

package com.example.dbhytcs.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class HytcSQLiteOpenHelper extends SQLiteOpenHelper{

    private static String name = "hytc.db";
    private static Integer version = 2;

    public HytcSQLiteOpenHelper(Context context) {
        super(context, name, null, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE user(id integer primary key autoincrement,name varchar(20))");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("alter table user add column phone varchar(11)");
    }


}

3.DBTest.java

package com.example.dbhytcs.test;

import com.example.dbhytcs.db.HytcSQLiteOpenHelper;

import android.database.sqlite.SQLiteDatabase;
import android.test.AndroidTestCase;

public class DBTest extends AndroidTestCase{

    private HytcSQLiteOpenHelper helper;

    public void testInsert(){
        helper = new HytcSQLiteOpenHelper(getContext());
        SQLiteDatabase db = helper.getWritableDatabase();
        for (int i = 0; i < 20; i++) {
            //执行sql语句
            db.execSQL("insert into user(name,phone) values('chj"+i+"','15962203803')");
        }
        db.close();
    }
}

4.在activity_main.xml中定义ListView控件id=lv_users
5.MainActivity.java

package com.example.dbhytcs;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.example.dbhytcs.db.HytcSQLiteOpenHelper;

public class MainActivity extends Activity {

    // 声明控件
    private ListView lv_users;

    private HytcSQLiteOpenHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 获取控件对象
        lv_users = (ListView) findViewById(R.id.lv_users);

        helper = new HytcSQLiteOpenHelper(this);

        Cursor c = helper.getReadableDatabase().rawQuery(
                "select id as _id,name,phone from user", null);

        // 创建adapter适配器对象
        ListAdapter adapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_expandable_list_item_2, c,
                new String[] { "name", "phone" }, new int[] {
                        android.R.id.text1, android.R.id.text2 },CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        //设置适配器
        lv_users.setAdapter(adapter);
    }
}

6.演示效果
这里写图片描述

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(数据库,ListView)