SQLite之采用ListView实现数据列表显示
用ListView实现数据列表显示 注意:在用SimpleCursorAdapter适配器时,如果查询语句为select*fromstudentwhereid=?时,而且数据库没有_id字段的话,运行后会报如下的错误
因为Cursor游标查询规定了数据库的id为_id。 解决办法:为数据库添加_id字段或者改查询sql 改为: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;
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |