SQLite的事务处理和listview的使用

来源:互联网 发布:网络编程毕业设计 编辑:程序博客网 时间:2024/05/18 16:39


记得我在博客里写过事务的特点如原子性,隔离性,一致性,持久性。下面就结合android的sqlite来说下,这次的博客会把listview也结合起来用。实际上android里的事务和我们数据库里的是一样的。也是开启事务,操作,提交事务。如果出现问题就回滚。

 public void Transaction(){   SQLiteDatabase database=db.getReadableDatabase();     database.beginTransaction();  //开启事务   try{  String sql1="update student set username='lili' where userid=2";   String sql2="update student set username='lucy' where userid=3";   database.execSQL(sql1);  database.execSQL(sql2);  database.setTransactionSuccessful();  //设置事务的状态,这句不写事务就会回滚   }finally{   database.endTransaction();  //结束事务   }   }


 

上面这段代码就是一个简单的事务操作,需要注意的就是要捕获异常,这样事务就会被结束掉可以节约数据库资源。

事务的操作就是这样,下面就介绍下listview的使用,我们理解成列表就可以了。界面如下

我们可以把这个界面拆成2个,主界面就只有“用户id”,“用户名”,“用户住址”也就是列表的头,主界面如下

<?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"    ><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="horizontal"  android:layout_width="wrap_content"  android:layout_height="wrap_content">  <TextView    android:layout_width="60dip"    android:layout_height="wrap_content"    android:text="用户id"  />   <TextView    android:layout_width="60dip"    android:layout_height="wrap_content"     android:text="用户名"  />    <TextView    android:layout_width="60dip"    android:layout_height="wrap_content"    android:text="用户住址"  /></LinearLayout>    <ListView    android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:id="@+id/listview"   /></LinearLayout>


这里的listview要定义一个id提供后面数据绑定使用,含有内容的显示界面也比较简单,也就是几个textview

<?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="horizontal"  android:layout_width="wrap_content"  android:layout_height="wrap_content">  <TextView    android:layout_width="60dip"    android:layout_height="wrap_content"    android:id="@+id/userid"  />   <TextView    android:layout_width="60dip"    android:layout_height="wrap_content"    android:id="@+id/username"  />    <TextView    android:layout_width="90dip"    android:layout_height="wrap_content"    android:id="@+id/address"  /></LinearLayout>


这样界面的部分就OK了,接下来就是读取数据了,之后显示在listview中,在这里就提供2种方法来显示数据

(1)方法1

package org.lxh.db;import java.util.*;import org.lxh.service.StudentService;import org.lxh.vo.Student;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.SimpleCursorAdapter;import android.widget.Toast;public class DBActivity extends Activity {    private StudentService service;    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        this.service=new StudentService(this);        ListView view=(ListView)this.findViewById(R.id.listview);        List<Student> all=this.service.fiandAll();        List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();        //逐个取出元素        Iterator<Student> it=all.iterator();        Student stu=null;        while(it.hasNext()){        stu=new Student();        stu=it.next();        HashMap<String,Object> map=new HashMap<String,Object>();        map.put("userid", stu.getUserid());        map.put("username", stu.getUsername());        map.put("address", stu.getAddress());        data.add(map);        }        //数据绑定        SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.listview, new String[]{"userid","username","address"},new int[]{R.id.userid,R.id.username,R.id.address});        view.setAdapter(adapter);        //添加列表项监听事件        view.setOnItemClickListener(new OnItemClickListener(){public void onItemClick(AdapterView<?> parent, View view,int position, long id) {   ListView listview=(ListView)parent;   HashMap<String,Object> hash=(HashMap<String,Object>)listview.getItemAtPosition(position);   Toast.makeText(DBActivity.this, hash.get("userid").toString(), 1).show();}});            
      }}


这里的数据绑定,使用的是SimpleAdapter,我们首先要做的就是把数据逐个取出来存入一个HashMap,如下所示

HashMap<String,Object> map=new HashMap<String,Object>();

这里的hashmap存储的是泛型数据,这个集合的泛型不能随便修改,接下来的工作就是把这个集合当做list的泛型

List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();

最后要记得把这个map添加到集合里

对于 

SimpleAdapter adapter=new SimpleAdapter(this, data, R.layout.listview, new String[]{"userid","username","address"},new int[]{R.id.userid,R.id.username,R.id.address});
        view.setAdapter(adapter);

第四个参数里的"userid","username","address"是map集合里的key,最后一个参数是textview,也就是数据界面里的textview.后面还加了个监听,只要点击textview就会显示用户id,android就会通过textview的位置读取内容。

这里把先读数据的代码先贴出来

 public List<Student> fiandAll(){   List<Student> all=new ArrayList<Student>();   String sql="select * from student";   SQLiteDatabase database=db.getReadableDatabase();  //使用getReadableDatabase取得SQLiteDatabase   Cursor cursor=database.rawQuery(sql, null);  //得到游标,类似resultset   Student stu;   while(cursor.moveToNext()){  //移动游标   int id=cursor.getInt(cursor.getColumnIndex("userid"));   String name=cursor.getString(cursor.getColumnIndex("username"));   String address=cursor.getString(cursor.getColumnIndex("address"));   stu=new Student();   stu.setUserid(id);   stu.setUsername(name);   stu.setAddress(address);   all.add(stu);   }   cursor.close();  //关闭游标   return all;   }


(2)游标适配器

下面是读数据的代码

 public Cursor fiandAllCursor(){   List<Student> all=new ArrayList<Student>();   String sql="select userid as _id,username,address from student";   SQLiteDatabase database=db.getReadableDatabase();  //使用getReadableDatabase取得SQLiteDatabase   Cursor cursor=database.rawQuery(sql, null);  //得到游标,类似resultset     //cursor.close();  //这里不可以关闭游标   return cursor;   }


这里为主键的列取了别名是因为android内部建议主键设置为_id,但是不可能每个表的主键的名称都是_id

 Cursor all=this.service.fiandAllCursor();  //使用游标适配器        SimpleCursorAdapter cadapter=new SimpleCursorAdapter(this, R.layout.listview,all, new String[]{"_id","username","address"},new int[]{R.id.userid,R.id.username,R.id.address});        view.setAdapter(cadapter);               //添加列表项监听事件        view.setOnItemClickListener(new OnItemClickListener(){public void onItemClick(AdapterView<?> parent, View view,int position, long id) {   ListView listview=(ListView)parent;   Cursor hash=(Cursor)listview.getItemAtPosition(position);  //取得被点击item的位置   int temp=hash.getInt(hash.getColumnIndex("_id"));   Toast.makeText(DBActivity.this, String.valueOf(temp), 1).show();  }});

这里的适配器参数顺序和上面的有点不同,而且第四个参数里的“usernam”,"address"和'_id'都是表的列名。其他地方没太大区别,上面的“_id”也不能写成别的。否则会出错

 

 

代码我已经上传上去了,有兴趣的自己下载下来跑下代码。