在android應用中,數據以列表的形式顯示通常是通過ListView來實現,下面是一個ListView入門的小例子
1.首先是主佈局文件main.xml
Xml代碼
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="60px"
android:layout_height="wrap_content"
android:id="@+id/idTitle"
android:text="編號"
/>
<TextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:layout_alignTop="@id/idTitle"
android:layout_toRightOf="@id/idTitle"
android:id="@+id/name"
android:text="姓名"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/name"
android:layout_toRightOf="@id/name"
android:text="年齡"
/>
</RelativeLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listView"
/>
</LinearLayout>
2.然後是列表所要用到的佈局文件,在layout目錄下新建personitem.xml文件,代碼如下
Xml代碼
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="60px"
android:layout_height="wrap_content"
android:id="@+id/personid"
/>
<TextView
android:layout_width="150px"
android:layout_height="wrap_content"
android:layout_alignTop="@id/personid"
android:layout_toRightOf="@id/personid"
android:id="@+id/personname"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/personname"
android:layout_toRightOf="@id/personname"
android:id="@+id/personage"
/>
</RelativeLayout>
用到的實體bean為Person,代碼如下
Java代碼
package com.lamp.domain;
public class Person {
private Integer personid = null;
private String name = null;
private Integer age = null;
public Person() {
}
public Person(String name,Integer age){
this.name = name;
this.age = age;
}
public Integer getPersonid() {
return personid;
}
public void setPersonid(Integer personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "name: " + this.name + ", age:" + this.age;
}
}
3.接著是Activity代碼
Java代碼
package com.lamp.db;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import com.lamp.domain.Person;
import com.lamp.service.PersonService;
public class DBActivity extends Activity {
private ListView listView = null;
private PersonService personService = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
personService = new PersonService(this);
listView = (ListView) this.findViewById(R.id.listView);
List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
List<Person> personList = personService.getScrollData(0, 10);
HashMap<String,String> map = null;
for(Person person : personList){
map = new HashMap<String,String>();
map.put("personid", String.valueOf(person.getPersonid()));
map.put("name", person.getName());
map.put("age", String.valueOf(person.getAge()));
data.add(map);
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, data,
R.layout.personitem,
new String[] { "personid", "name", "age" }, new int[]{R.id.personid,R.id.personname,R.id.personage});
listView.setAdapter(simpleAdapter);
/*
* 這是通過遊標在ListView控件上顯示數據,需要註意的是主鍵字段名id應改為_id,否則會報錯
Cursor cursor = personService.getRawScrollData(0, 10);
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.personitem,
cursor,
new String[] { "_id", "name", "age" }, new int[]{R.id.personid,R.id.personname,R.id.personage});
listView.setAdapter(simpleCursorAdapter);
*/
//為item選項設置監聽
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
ListView listView = (ListView)parent;
Map<String,String> map = (HashMap<String, String>)listView.getItemAtPosition(position);
Log.i("DBActivity", map.get("age"));
}
});
}
}
4.業務層代碼如下
Java代碼
package com.lamp.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.lamp.domain.Person;
public class PersonService {
private DataBaseOpenHelper dbHelper = null;
private SQLiteDatabase sqLiteDatabase = null;
public PersonService(Context context) {
dbHelper = new DataBaseOpenHelper(context);
sqLiteDatabase = dbHelper.getWritableDatabase();
}
public void save(Person person){
String sql = "insert into person(name,age) values (?,?)";
sqLiteDatabase.execSQL(sql, new Object[]{person.getName(),person.getAge()});
}
//指定刪除
public void delete(Integer personid){
String sql = "delete from person where personid=?";
sqLiteDatabase.execSQL(sql,new Object[]{personid});
}
//批量刪除
public void deletePersons(Integer… ids){
StringBuilder sb = new StringBuilder();
if(ids.length > 0){
for (int i = 0; i < ids.length; i++) {
sb.append('?').append(',');
}
sb.deleteCharAt(sb.length()-1);
String sql = "delete from person where personid in ("+ sb +")";
sqLiteDatabase.execSQL(sql,(Object[])ids);
}
}
//更新數據
public void update(Person person){
String sql = "update person set name=?,age=? where personid=?";
sqLiteDatabase.execSQL(sql, new Object[]{person.getName(),person.getAge(),person.getPersonid()});
}
//得到全部的結果集
public List<Person> getAllPersons(){
String sql = "select name,age from person";
Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
Person person = null;
List<Person> personList = new ArrayList<Person>();
while(cursor.moveToNext()){
String name = cursor.getString(0);
int age = cursor.getInt(1);
person = new Person(name,age);
personList.add(person);
}
return personList;
}
//分頁取數據
public List<Person> getScrollData(Integer start, Integer size){
String sql = "select personid, name,age from person limit ?,?";
Cursor cursor = sqLiteDatabase.rawQuery(sql, new String[]{String.valueOf(start),String.valueOf(size)});
List<Person> personList = new ArrayList<Person>();
Person person = null;
while(cursor.moveToNext()){
int personid = cursor.getInt(0);
String name = cursor.getString(1);
int age = cursor.getInt(2);
person = new Person(name,age);
person.setPersonid(personid);
personList.add(person);
}
return personList;
}
//返回遊標對象,當要在ListView中顯示數據時,主鍵的字段名需設定為_id,否則返回的Cursor對象會出錯
public Cursor getRawScrollData(Integer start, Integer size){
String sql = "select personid as _id, name,age from person limit ?,?";
return sqLiteDatabase.rawQuery(sql, new String[]{String.valueOf(start),String.valueOf(size)});
}
//返回表中總記錄條數
public int getCount(){
String sql = "select count(*) from person";
Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToNext()){
return cursor.getInt(0);
}
return 0;
}
}
5.由於用到瞭android的SQLite數據庫,對數據庫操作的工具類代碼如下
Java代碼
package com.lamp.service;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseOpenHelper extends SQLiteOpenHelper {
private static final String DBNAME = "android";
private static final int VERSION = 1;
public DataBaseOpenHelper(Context context) {
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String sql = "create table person (personid integer primary key autoincrement,name varchar(20),age integer)";
sqLiteDatabase.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
String sql = "drop table if exists person";
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
}
首先通過單元測試往數據庫中添加若幹條記錄,然後運行項目看到記錄以列表的形式顯示
作者“坐如松,動如風”