您的位置:首页 > 数据库

SQLite之采用ListView实现数据列表显示

2013-10-26 16:47 561 查看
用ListView实现数据列表显示



注意:在用SimpleCursorAdapter适配器时,如果查询语句为select * from student where id=? 时,而且数据库没有_id字段的话,运行后会报如下的错误



因为Cursor游标查询规定了数据库的id为_id。

解决办法:为数据库添加_id字段 或者 改查询sql

改为:select id as _id,name,phone from student where id=?





在layout文件夹下建items.xml

Items.xml



<LinearLayout xmlns: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



<LinearLayout xmlns: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

package com.example.entity;



public class Student {

private Integer id;

private String name;

private String phone;

private Double account;

public Student(Integer id,String name,String phone,Double account){

this.id=id;

this.name=name;

this.phone=phone;

this.account=account;

}

public Integer getId() {

return id;

}

public void setId(Integer id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

public Double getAccount() {

return account;

}

public void setAccount(Double account) {

this.account = account;

}

public String toString(){

return this.getId()+","+this.getName()+","+this.getPhone()+","+this.getAccount();

}



}





3.创建DBOpenHelper类 extends SQLiteOpenHelper 创建数据库







package com.example.sqlite;



import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteDatabase.CursorFactory;

import android.database.sqlite.SQLiteOpenHelper;



public class DBOpenHelper extends SQLiteOpenHelper {



public DBOpenHelper(Context context) {

super(context, "olay", null, 3);

// TODO Auto-generated constructor stub

}



@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("create table student(id integer primary key autoincrement,name varchar(20)),phone varchar(20) null");

}



/**

* 版本更新后调用次方法

*/

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

db.execSQL("alter table student add account Double null");

}



}







4.创建StudentService类 (方法的操作类)
StudentService.java

package com.example.server;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.example.entity.Student;
import com.example.sqlite.DBOpenHelper;

public class StudentService {
private DBOpenHelper helper;
public StudentService(Context context) {
helper = new DBOpenHelper(context);
}
/**

* 获取指定的记录

* @param offset 跳过前面offset记录

* @param maxsize 最多显示maxsize条记录

* @return List<Student>

*/

public List<Student> getScrollDate(int offset,int maxsize){

List<Student> list = new ArrayList<Student>();

SQLiteDatabase db = helper.getReadableDatabase();

Cursor cursor=db.rawQuery("select * from student order by id asc limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxsize)});

while(cursor.moveToNext()){

int sId = cursor.getInt(cursor.getColumnIndex("id"));

String name = cursor.getString(cursor.getColumnIndex("name"));

String phone = cursor.getString(cursor.getColumnIndex("phone"));

Double account = cursor.getDouble(cursor.getColumnIndex("account"));

list.add(new Student(sId,name,phone,account));

}

cursor.close();

return list;

}

/**

* 获取指定的记录

* @param offset 跳过前面offset记录

* @param maxsize 最多显示maxsize条记录

* @return Cursor

*/

public Cursor getScrollDateReturnCursor(int offset,int maxsize){

SQLiteDatabase db = helper.getReadableDatabase();

/*Cursor cursor=db.rawQuery("select id as _id,name,phone,account from student order by id asc limit ?,?",

new String[]{String.valueOf(offset),String.valueOf(maxsize)});*/

Cursor cursor=db.rawQuery("select * from student order by id asc limit ?,?",

new String[]{String.valueOf(offset),String.valueOf(maxsize)});

return cursor; //不能关闭cursor,不然返回不了cursor

}

}


6.MainActivity.java

package com.example.sqlite;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.example.entity.Student;
import com.example.server.StudentService;

import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
private ListView listView = null;
private StudentService student=null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
student = new StudentService(this); //实例化StudentService类
listView = (ListView) findViewById(R.id.listView); //获取ListView组件
// ShowListViewDate1(); //使用SimpleAdapter来绑定数据
//ShowListViewDate2(); //使用SimpleCursorAdapter绑定数据
ShowListViewDate3(); //自定义适配器

//给listView添加事件监听

listView.setOnItemClickListener(new OnItemClickListener() {



@Override

public void onItemClick(AdapterView<?> parent, View view,

int position, long id) {

//parent是ListView , View是选中的一行view ,position是集合中一条数据的下标

Student s=(Student) parent.getItemAtPosition(position);

Toast.makeText(MainActivity.this, "姓名是:"+s.getName()+" 电话号码是:"+s.getPhone(), Toast.LENGTH_LONG).show();

}

});
}

//使用SimpleAdapter来绑定数据
private void ShowListViewDate1() {
List<Student> s=student.getScrollDate(0, 20); //分页查询数据

List<Map<String,Object>> data = new ArrayList<Map<String,Object>>();
for(Student students:s){
Map<String,Object> map = new HashMap<String, Object>();
map.put("name", students.getName());
map.put("phone", students.getPhone());
map.put("account", students.getAccount());
data.add(map);
}

SimpleAdapter adapter =new SimpleAdapter(MainActivity.this, data, R.layout.items,
new String[]{"name","phone","account"}, new int[]{R.id.name,R.id.phone,R.id.account});

listView.setAdapter(adapter);
}

//使用SimpleCursorAdapter绑定数据
private void ShowListViewDate2(){
Cursor cursor =student.getScrollDateReturnCursor(0, 20);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.items, cursor,
new String[]{"name","phone","account"}, new int[]{R.id.name,R.id.phone,R.id.account});
listView.setAdapter(adapter);
}
//自定义适配器

private void ShowListViewDate3(){

List<Student> s=student.getScrollDate(0, 20); //分页查询数据

MyAdapter adapter = new MyAdapter(this, s, R.layout.items);

listView.setAdapter(adapter);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}




自定义适配器类 MyAdapter ,extends BaseAdapter

MyAdapter.java

package com.example.sqlite;

import java.util.List;

import com.example.entity.Student;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {
private List<Student> student; //绑定的数据
private int resource; //绑定的条目界面 R.layout.items
private LayoutInflater inflater; //把xml布局文件生成view对象

public MyAdapter(Context context,List<Student> student,int resource){
this.inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //获取上下文的LayoutInflater
this.student=student;
this.resource=resource;
}
@Override
public int getCount() {
return student.size();
}

@Override
public Object getItem(int position) {
return student.get(position);
}

@Override
public long getItemId(int position) {
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
convertView=inflater.inflate(resource, null); //从指定的xml资源中inflate出一个新的View
}
TextView name = (TextView) convertView.findViewById(R.id.name); //取得组件
TextView phone= (TextView) convertView.findViewById(R.id.phone); //取得组件
TextView account = (TextView) convertView.findViewById(R.id.account); //取得组件
Student s = student.get(position); //在List<Student>中获取要绑定的数据
//绑定数据到TextView中
name.setText(s.getName());
phone.setText(s.getPhone());
account.setText(s.getAccount().toString());
return convertView;
}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: