用ListView实现数据列表显示
注意:在用SimpleCursorAdapter适配器时,如果查询语句为select*fromstudentwhereid=?时,而且数据库没有_id字段的话,运行后会报如下的错误
改为:selectidas_id,name,phonefromstudentwhereid=?
在layout文件夹下建items.xml
Items.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
<TextView
android:id="@+id/name"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:textSize="24px"
android:layout_marginLeft="15px"
/>
<TextView
android:id="@+id/phone"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:textSize="24px"
/>
<TextView
android:id="@+id/account"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="24px"
/>
</LinearLayout>
Activity_main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="@+id/name"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="@string/name"
android:layout_marginLeft="15px"
android:textSize="28px"
/>
<TextView
android:id="@+id/phone"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:text="@string/phone"
android:textSize="28px"
/>
<TextView
android:id="@+id/account"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/account"
android:textSize="28px"
/>
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
2.创建实体类(javabean)
Student.java
packagecom.example.entity;
publicclassStudent{
privateIntegerid;
privateStringname;
privateStringphone;
privateDoubleaccount;
publicStudent(Integerid,Stringname,Stringphone,Doubleaccount){
this.id=id;
this.name=name;
this.phone=phone;
this.account=account;
}
publicIntegergetId(){
returnid;
}
publicvoidsetId(Integerid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicStringgetPhone(){
returnphone;
}
publicvoidsetPhone(Stringphone){
this.phone=phone;
}
publicDoublegetAccount(){
returnaccount;
}
publicvoidsetAccount(Doubleaccount){
this.account=account;
}
publicStringtoString(){
returnthis.getId()+","+this.getName()+","+this.getPhone()+","+this.getAccount();
}
}
3.创建DBOpenHelper类extendssqliteOpenHelper创建数据库
packagecom.example.sqlite;
importandroid.content.Context;
importandroid.database.sqlite.sqliteDatabase;
importandroid.database.sqlite.sqliteDatabase.CursorFactory;
importandroid.database.sqlite.sqliteOpenHelper;
publicclassDBOpenHelperextendssqliteOpenHelper{
publicDBOpenHelper(Contextcontext){
super(context,"olay",null,3);
//TODOAuto-generatedconstructorstub
}
@Override
publicvoidonCreate(sqliteDatabasedb){
db.execsql("createtablestudent(idintegerprimarykeyautoincrement,namevarchar(20)),phonevarchar(20)null");
/**
*/
publicvoidonUpgrade(sqliteDatabasedb,intoldVersion,intnewVersion){
db.execsql("altertablestudentaddaccountDoublenull");
4.创建StudentService(方法的操作类)
.java
packagecom.example.server;
importjava.util.ArrayList;
importjava.util.List;
importandroid.content.Context;
importandroid.database.Cursor;
importandroid.database.sqlException;
importandroid.database.sqlite.sqliteDatabase;
importcom.example.entity.Student;
importcom.example.sqlite.DBOpenHelper;
publicclassStudentService{
privateDBOpenHelperhelper;
publicStudentService(Contextcontext){
helper=newDBOpenHelper(context);
}
/**
*获取指定的记录
*@paramoffset跳过前面offset记录
*@parammaxsize最多显示maxsize条记录
*@returnList<Student>
*/
publicList<Student>getScrollDate(intoffset,intmaxsize){
List<Student>list=newArrayList<Student>();
sqliteDatabasedb=helper.getReadableDatabase();
Cursorcursor=db.rawQuery("select*fromstudentorderbyidasclimit?,?",newString[]{String.valueOf(offset),String.valueOf(maxsize)});
while(cursor.moveToNext()){
intsId=cursor.getInt(cursor.getColumnIndex("id"));
Stringname=cursor.getString(cursor.getColumnIndex("name"));
Stringphone=cursor.getString(cursor.getColumnIndex("phone"));
Doubleaccount=cursor.getDouble(cursor.getColumnIndex("account"));
list.add(newStudent(sId,phone,account));
}
cursor.close();
returnlist;
}
/**
*获取指定的记录
*@paramoffset跳过前面offset记录
*@parammaxsize最多显示maxsize条记录
*@returnCursor
*/
publicCursorgetScrollDateReturnCursor(intoffset,intmaxsize){
sqliteDatabasedb=helper.getReadableDatabase();
/*Cursorcursor=db.rawQuery("selectidas_id,accountfromstudentorderbyidasclimit?,?",
newString[]{String.valueOf(offset),String.valueOf(maxsize)});*/
Cursorcursor=db.rawQuery("select*fromstudentorderbyidasclimit?,
newString[]{String.valueOf(offset),String.valueOf(maxsize)});
returncursor;//不能关闭cursor,不然返回不了cursor
}
}
6.MainActivity.java
packagecom.example.sqlite;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importcom.example.entity.Student;
importcom.example.server.StudentService;
importandroid.os.Bundle;
importandroid.app.Activity;
importandroid.database.Cursor;
importandroid.support.v4.widget.SimpleCursorAdapter;
importandroid.view.Menu;
importandroid.widget.ListView;
importandroid.widget.SimpleAdapter;
publicclassMainActivityextendsActivity{
privateListViewlistView=null;
privateStudentServicestudent=null;
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
student=newStudentService(this);//实例化StudentService类
listView=(ListView)findViewById(R.id.listView);//获取ListView组件
//ShowListViewDate1();//使用SimpleAdapter来绑定数据
//ShowListViewDate2();//使用SimpleCursorAdapter绑定数据
ShowListViewDate3();//自定义适配器
//给listView添加事件监听
listView.setOnItemClickListener(newOnItemClickListener(){
@Override
publicvoidonItemClick(AdapterView<?>parent,Viewview,
intposition,longid){
//parent是ListView,View是选中的一行view,position是集合中一条数据的下标
Students=(Student)parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this,"姓名是:"+s.getName()+"电话号码是:"+s.getPhone(),Toast.LENGTH_LONG).show();
}
});
//使用SimpleAdapter来绑定数据
privatevoidShowListViewDate1(){
List<Student>s=student.getScrollDate(0,20);//分页查询数据
List<Map<String,Object>>data=newArrayList<Map<String,Object>>();
for(Studentstudents:s){
Map<String,Object>map=newHashMap<String,Object>();
map.put("name",students.getName());
map.put("phone",students.getPhone());
map.put("account",students.getAccount());
data.add(map);
SimpleAdapteradapter=newSimpleAdapter(MainActivity.this,data,R.layout.items,
newString[]{"name","phone","account"},newint[]{R.id.name,R.id.phone,R.id.account});
listView.setAdapter(adapter);
//使用SimpleCursorAdapter绑定数据
privatevoidShowListViewDate2(){
Cursorcursor=student.getScrollDateReturnCursor(0,20);
SimpleCursorAdapteradapter=newSimpleCursorAdapter(this,cursor,255)">newString[]{"name",255)">}
//自定义适配器
privatevoidShowListViewDate3(){
List<Student>s=student.getScrollDate(0,20);//分页查询数据
MyAdapteradapter=newMyAdapter(this,s,R.layout.items);
listView.setAdapter(adapter);
publicbooleanonCreateOptionsMenu(Menumenu){
//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
getMenuInflater().inflate(R.menu.main,menu);
returntrue;
自定义适配器类MyAdapter,extendsBaseAdapter
MyAdapter.java
importandroid.content.Context;
importandroid.view.LayoutInflater;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.TextView;
publicclassMyAdapterextendsBaseAdapter{
privateList<Student>student;//绑定的数据
privateintresource;//绑定的条目界面R.layout.items
privateLayoutInflaterinflater;//把xml布局文件生成view对象
publicMyAdapter(Contextcontext,List<Student>student,intresource){
this.inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//获取上下文的LayoutInflater
this.student=student;
this.resource=resource;
publicintgetCount(){
returnstudent.size();
publicObjectgetItem(intposition){
returnstudent.get(position);
publiclonggetItemId(intposition){
returnposition;
publicViewgetView(intposition,ViewconvertView,ViewGroupparent){
if(convertView==null){
convertView=inflater.inflate(resource,null);//从指定的xml资源中inflate出一个新的View
TextViewname=(TextView)convertView.findViewById(R.id.name);//取得组件
TextViewphone=(TextView)convertView.findViewById(R.id.phone);//取得组件
TextViewaccount=(TextView)convertView.findViewById(R.id.account);//取得组件
Students=student.get(position);//在List<Student>中获取要绑定的数据
//绑定数据到TextView中
name.setText(s.getName());
phone.setText(s.getPhone());
account.setText(s.getAccount().toString());
returnconvertView;
原文链接:https://www.f2er.com/sqlite/200999.html