ListView显示数据库的数据-SimpleCursorAdapter的使用
Posted Veer Han
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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显示数据库的数据-SimpleCursorAdapter的使用的主要内容,如果未能解决你的问题,请参考以下文章
wpf的listview中无数据的时候在表单中显示无数据显示
在winform中,怎么做到一个按钮,,点击一下在listview显示一组新数据,然后点一下listview显示原来的数据.