Android 事务操作和数据显示(ListView的使用)

来源:互联网 发布:js产生不重复的随机数 编辑:程序博客网 时间:2024/06/05 08:02

//目录结构


//编写Bean类

package sn.len.transandlistview.domain;public class PersonBean{private Integer id;private String name;private String amount;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 getAmount() {return amount;}public void setAmount(String amount) {this.amount = amount;}@Overridepublic String toString() {return "PersonBean [id=" + id + ", name=" + name + ", amount=" + amount+ "]";}public PersonBean(Integer id, String name) {this.id = id;this.name = name;}public PersonBean() {}}


//编写DB类

DBOpenHelper.java 创建表,以及数据库

package sn.len.transandlistview;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class DBOpenHelper extends SQLiteOpenHelper{private static final String TAG="testinfo";private static final String DBNAME="transdb.db";private static final int DBVERSION=1;public DBOpenHelper(Context context) {super(context,DBNAME,null,DBVERSION);Log.i(TAG,"come in there");}@Overridepublic void onCreate(SQLiteDatabase db){db.execSQL("create table PersonBean(id integer primary key autoincrement,name varchar(20),amount varchar(20))");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}}

//编写业务类,Service

package sn.len.transandlistview.service;import java.util.ArrayList;import java.util.List;import sn.len.transandlistview.DBOpenHelper;import sn.len.transandlistview.domain.PersonBean;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.util.Log;public class TransListviewService{private DBOpenHelper dbopen;public TransListviewService(Context context){this.dbopen=new DBOpenHelper(context);this.dbopen.getWritableDatabase();}//添加数据public void save(PersonBean person){SQLiteDatabase sqld=dbopen.getWritableDatabase();Log.i("name", person.getName());Log.i("amount", person.getAmount());sqld.execSQL("insert into PersonBean(name,amount) values(?,?)",new Object[]{person.getName(),person.getAmount()});}//事务处理public void trans(){SQLiteDatabase sqld=dbopen.getWritableDatabase();sqld.beginTransaction();sqld.execSQL("update PersonBean set name=? where id=?",new Object[]{"admin",1});sqld.execSQL("update PersonBean set name=? where id=?",new Object[]{"administrator",2});sqld.setTransactionSuccessful();sqld.endTransaction();}//查询分页public List<PersonBean> selectGroup(Integer offset,Integer maxRow){SQLiteDatabase sqld=dbopen.getWritableDatabase();List<PersonBean> listPb=new ArrayList<PersonBean>();Cursor cursor=sqld.rawQuery("select * from PersonBean limit ?,?",new String[]{offset.toString(),maxRow.toString()});while(cursor.moveToNext()){PersonBean pb=new PersonBean();pb.setId(cursor.getInt(cursor.getColumnIndex("id")));pb.setName(cursor.getString(cursor.getColumnIndex("name")));pb.setAmount(cursor.getString(cursor.getColumnIndex("amount")));listPb.add(pb);}return listPb;}//通过返回邮标来得到显示的数据public Cursor getCursor(Integer offset,Integer maxRow){SQLiteDatabase sqld=dbopen.getWritableDatabase();//如果使用邮标那么ID必需设置尖_id才行。Cursor cursor=sqld.rawQuery("select id as _id,name,amount from PersonBean limit ?,?",new String[]{offset.toString(),maxRow.toString()});return cursor;}}

//编写Junit类,TransListviewServiceTest.java注意配置XML

package sn.len.transandlistview.service.test;import java.util.List;import sn.len.transandlistview.domain.PersonBean;import sn.len.transandlistview.service.TransListviewService;import android.test.AndroidTestCase;import android.util.Log;public class TransListviewServiceTest extends AndroidTestCase {private static final String TAG="content";//测试创建数据库public void testCreateDB(){new TransListviewService(this.getContext());}//保存数据public void testSave(){TransListviewService tls=new TransListviewService(this.getContext());PersonBean person=new PersonBean();person.setName("xiaoyang");person.setAmount("1000");tls.save(person);person.setName("xiaoyang1");person.setAmount("1000");tls.save(person);person.setName("xiaoyang2");person.setAmount("1000");tls.save(person);person.setName("xiaoyang3");person.setAmount("1000");tls.save(person);person.setName("xiaoyang4");person.setAmount("1000");tls.save(person);}public void select(){TransListviewService tls=new TransListviewService(this.getContext());List<PersonBean> person=tls.selectGroup(0,10);for(PersonBean bean:person){Log.i(TAG,bean.toString());}}public void testTrans(){TransListviewService tls=new TransListviewService(this.getContext());tls.trans();}}

//编写Item XML

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="horizontal"     >    <TextView         android:id="@+id/id"        android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="aaa"        />    <TextView         android:id="@+id/name"        android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="aaa"        />    <TextView         android:id="@+id/amount"        android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="aaa"        /></LinearLayout>

//编写主XML

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical"     ><LinearLayout     android:layout_width="fill_parent"    android:layout_height="wrap_content"        >    <TextView         android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="编号"        />    <TextView         android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="姓名"        />    <TextView         android:layout_width="100dip"        android:layout_height="wrap_content"        android:text="存款"        /></LinearLayout>    <ListView         android:layout_width="fill_parent"        android:layout_height="fill_parent"        android:id="@+id/listView"        >            </ListView></LinearLayout>

//编写控制层类NineActivity.java

package sn.len.transandlistview;import java.util.List;import sn.len.transandlistview.domain.PersonBean;import sn.len.transandlistview.service.TransListviewService;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.AdapterView.OnItemClickListener;import android.widget.ListView;import android.widget.SimpleCursorAdapter;public class NineActivity extends Activity {private static final String TAG="Content";    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        TransListviewService tls=new TransListviewService(this);        List<PersonBean> personBean=tls.selectGroup(0, 10);        ListView listView=(ListView)findViewById(R.id.listView);        /*                List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();        for(PersonBean pb:personBean)        {        HashMap<String,Object> hashMap=new HashMap<String,Object>();        hashMap.put("id", pb.getId());        hashMap.put("name", pb.getName());        hashMap.put("amount", pb.getAmount());        data.add(hashMap);        }        //第一种方式        SimpleAdapter simpleAdp=new SimpleAdapter        (this, data, R.layout.item,new String[]{"id","name","amount"},new int[]{R.id.id,R.id.name,R.id.amount});        listView.setAdapter(simpleAdp);        //设置监听        listView.setOnItemClickListener        (        new OnItemClickListener()        {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {/* * parent 这里的parent就是这个ListView * view 第二个参数view是指“下拉列表”中的你所点击的那个“条目”,而在ListView中“条目”的View是TextView * postition 第三个参数、第四个参数就是你所点击的“条目”在“下拉列表”中的位置和条目的id 基本累同 * ListView lview=(ListView)parent;//因为存进去的每个TextView就是HashMap,所以取出来也是HashMap<String,Object> hash=(HashMap<String,Object>)lview.getItemAtPosition(position);Iterator it=hash.entrySet().iterator();while(it.hasNext()){Entry  obj = (Entry)it.next();Log.i(TAG,obj.getKey()+""+obj.getValue());}}}        );*/                //第二种方式,使用游标        Cursor cursor=tls.getCursor(0, 10);        SimpleCursorAdapter sca=new SimpleCursorAdapter(this, R.layout.item, cursor, new String[]{"_id","name","amount"},new int[]{R.id.id,R.id.name,R.id.amount});        listView.setAdapter(sca);                //设置监听        listView.setOnItemClickListener        (        new OnItemClickListener()        {@Overridepublic void onItemClick(AdapterView<?> parent, View view,int position, long id) {//参数与上面相同ListView lview=(ListView)parent;//用CursorCursor cu=(Cursor)lview.getItemAtPosition(position);//得到数据int _id=cu.getInt(cu.getColumnIndex("_id"));Log.i(TAG,_id+"");}        }        );            }}

//结果