您的位置:首页 > 数据库

Project——SQLite数据库操作(采用ListView实现数据列表展现)

2012-05-05 20:54 531 查看
1、

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="cn.itcast.db"

android:versionCode="1"

android:versionName="1.0">

<application android:icon="@drawable/icon" android:label="@string/app_name">

<uses-library android:name="android.test.runner" />

<activity android:name=".MainActivity"

android:label="@string/app_name">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<provider android:name=".PersonContentProvider" android:authorities="cn.itcast.provides.personprovider"/>

</application>

<uses-sdk android:minSdkVersion="8" />

<instrumentation android:name="android.test.InstrumentationTestRunner"

android:targetPackage="cn.itcast.db" android:label="Tests for My App" />

</manifest>

2、

package cn.itcast.db;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import cn.itcast.domain.Person;

import cn.itcast.service.PersonService;

import android.app.Activity;

import android.content.ContentResolver;

import android.content.ContentValues;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.util.Log;

import android.view.View;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.ListView;

import android.widget.SimpleAdapter;

import android.widget.SimpleCursorAdapter;

import android.widget.Toast;

import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

private static final String TAG = "MainActivity";

private ListView listView;

private PersonService service;



@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);



Button button = (Button)this.findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

ContentResolver contentResolver = getContentResolver();

Uri insertUri = Uri.parse("content://cn.itcast.provides.personprovider/person");

ContentValues values = new ContentValues();

values.put("name", "laofang");

values.put("phone", "13800029333");

values.put("amount", "1000");

contentResolver.insert(insertUri, values);

}

});



listView = (ListView)this.findViewById(R.id.listView);

service = new PersonService(this);

/* List<Person> persons = service.getScrollData(0, 5);

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

for(Person person : persons){

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

item.put("name", person.getName());

item.put("phone", person.getPhone());

item.put("amount", person.getAmount());

data.add(item);

}

SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item,

new String[]{"name","phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});

listView.setAdapter(adapter);



listView.setOnItemClickListener(new ItemClickListener());

*/

Cursor cursor = service.getCursorScrollData(0, 5);

SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.item, cursor,

new String[]{"name","phone","amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});

listView.setAdapter(cursorAdapter);

listView.setOnItemClickListener(new ItemClickListener());

}



private final class ItemClickListener implements OnItemClickListener{

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

ListView lView = (ListView)parent;

/*HashMap<String, Object> item = (HashMap<String, Object>)lView.getItemAtPosition(position);

Log.i(TAG, item.get("name").toString());

Toast.makeText(MainActivity.this, item.get("name").toString(), 1).show();*/

Cursor cursor = (Cursor)lView.getItemAtPosition(position);

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

Toast.makeText(MainActivity.this, name, 1).show();

}



}

}

3、

package cn.itcast.db;

import cn.itcast.service.DBOpenHelper;

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.net.Uri;

public class PersonContentProvider extends ContentProvider {

private static final UriMatcher sMatcher = new UriMatcher(UriMatcher.NO_MATCH);

private static final int PERSONS = 1;

private static final int PERSON = 2;

private DBOpenHelper dbOpenHelper;



static{

sMatcher.addURI("cn.itcast.provides.personprovider", "person", PERSONS);

sMatcher.addURI("cn.itcast.provides.personprovider", "person/#", PERSON);

}

// content://cn.itcast.provides.personprovider/person

@Override

public Uri insert(Uri uri, ContentValues values) {

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

switch (sMatcher.match(uri)) {

case PERSONS:

long rowid = db.insert("person", "name", values);

getContext().getContentResolver().notifyChange(uri, null);

return ContentUris.withAppendedId(uri, rowid);

default:

throw new IllegalArgumentException("Unknown Uri:"+ uri);

}

}

// content://cn.itcast.provides.personprovider/person 删除表中的所有记录

// content://cn.itcast.provides.personprovider/person/10 删除表中指定id的记录

@Override

public int delete(Uri uri, String selection, String[] selectionArgs) {

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

int num = 0;

switch (sMatcher.match(uri)) {

case PERSONS:

num = db.delete("person", selection, selectionArgs);

break;

case PERSON:

long personid = ContentUris.parseId(uri);

String where = "personid="+ personid;

if(selection!=null && !"".equals(selection)){

where = where + " and "+ selection;

}

num = db.delete("person", where, selectionArgs);

break;

default:

throw new IllegalArgumentException("Unknown Uri:"+ uri);

}

getContext().getContentResolver().notifyChange(uri, null);

return num;

}

@Override

public String getType(Uri uri) {// gif image/gif text/plain

switch (sMatcher.match(uri)) {

case PERSONS:

return "vnd.android.cursor.dir/person";

case PERSON:

return "vnd.android.cursor.item/person";

default:

throw new IllegalArgumentException("Unknown Uri:"+ uri);

}

}

@Override

public boolean onCreate() {

this.dbOpenHelper = new DBOpenHelper(this.getContext());

return true;

}

// content://cn.itcast.provides.personprovider/person 获取表中的所有记录

// content://cn.itcast.provides.personprovider/person/10 获取表中指定id的记录

@Override

public Cursor query(Uri uri, String[] projection, String selection,

String[] selectionArgs, String sortOrder) {

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

switch (sMatcher.match(uri)) {

case PERSONS:

return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);



case PERSON:

long personid = ContentUris.parseId(uri);

String where = "personid="+ personid;

if(selection!=null && !"".equals(selection)){

where = where + " and "+ selection;

}

return db.query("person", projection, where, selectionArgs, null, null, sortOrder);



default:

throw new IllegalArgumentException("Unknown Uri:"+ uri);

}

}

// content://cn.itcast.provides.personprovider/person 更新表中的所有记录

// content://cn.itcast.provides.personprovider/person/10 更新表中指定id的记录

@Override

public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

int num = 0;

switch (sMatcher.match(uri)) {

case PERSONS:

num = db.update("person", values, selection, selectionArgs);

break;

case PERSON:

long personid = ContentUris.parseId(uri);

String where = "personid="+ personid;

if(selection!=null && !"".equals(selection)){

where = where + " and "+ selection;

}

num = db.update("person", values, where, selectionArgs);

break;

default:

throw new IllegalArgumentException("Unknown Uri:"+ uri);

}

getContext().getContentResolver().notifyChange(uri, null);

return num;

}

}

4、

package cn.itcast.db;

import java.util.List;

import cn.itcast.domain.Person;

import cn.itcast.service.OtherPersonService;

import android.test.AndroidTestCase;

import android.util.Log;

public class OtherPersonServiceTest extends AndroidTestCase {

private static final String TAG = "PersonServiceTest";



public void testSave() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

Person person = new Person();

person.setName("zhangxiaoxiao");

person.setPhone("13671555567");

service.save(person);



Person person2 = new Person();

person2.setName("laobi");

person2.setPhone("13679993567");

service.save(person2);



Person person3 = new Person();

person3.setName("lili");

person3.setPhone("13888323567");

service.save(person3);



Person person4 = new Person();

person4.setName("zhaoxiaogang");

person4.setPhone("1367132300");

service.save(person4);

}



public void testFind() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

Person person = service.find(1);

Log.i(TAG, person.toString());

}



public void testUpdate() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

Person person = service.find(1);

person.setName("liming");

service.update(person);

}



public void testCount() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

Log.i(TAG, service.getCount()+"");

}



public void testScrollData() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

List<Person> persons = service.getScrollData(0, 3);

for(Person person : persons){

Log.i(TAG, person.toString());

}

}



public void testDelete() throws Throwable{

OtherPersonService service = new OtherPersonService(this.getContext());

service.delete(1);

}

}

5、

package cn.itcast.db;

import java.util.List;

import cn.itcast.domain.Person;

import cn.itcast.service.DBOpenHelper;

import cn.itcast.service.PersonService;

import android.test.AndroidTestCase;

import android.util.Log;

public class PersonServiceTest extends AndroidTestCase {

private static final String TAG = "PersonServiceTest";



public void testDBCreate() throws Throwable{

DBOpenHelper dbOpenHelper = new DBOpenHelper(this.getContext());

dbOpenHelper.getWritableDatabase();

}



public void testSave() throws Throwable{

PersonService service = new PersonService(this.getContext());

Person person = new Person();

person.setName("zhangxiaoxiao");

person.setPhone("13671555567");

person.setAmount(100);

service.save(person);



Person person2 = new Person();

person2.setName("laobi");

person2.setPhone("13679993567");

person2.setAmount(50);

service.save(person2);



Person person3 = new Person();

person3.setName("lili");

person3.setPhone("13888323567");

person3.setAmount(80);

service.save(person3);



Person person4 = new Person();

person4.setName("zhaoxiaogang");

person4.setPhone("1367132300");

person4.setAmount(90);

service.save(person4);

}



public void testFind() throws Throwable{

PersonService service = new PersonService(this.getContext());

Person person = service.find(1);

Log.i(TAG, person.toString());

}



public void testUpdate() throws Throwable{

PersonService service = new PersonService(this.getContext());

Person person = service.find(1);

person.setName("liming");

service.update(person);

}



public void testCount() throws Throwable{

PersonService service = new PersonService(this.getContext());

Log.i(TAG, service.getCount()+"");

}



public void testScrollData() throws Throwable{

PersonService service = new PersonService(this.getContext());

List<Person> persons = service.getScrollData(0, 3);

for(Person person : persons){

Log.i(TAG, person.toString());

}

}



public void testDelete() throws Throwable{

PersonService service = new PersonService(this.getContext());

service.delete(1);

}



public void testPayment() throws Throwable{

PersonService service = new PersonService(this.getContext());

service.payment();

}



}

6、

package cn.itcast.domain;

public class Person {

private Integer id;

private String name;

private String phone;

private Integer amount;



public Integer getAmount() {

return amount;

}

public void setAmount(Integer amount) {

this.amount = amount;

}

public Person(){}



public Person(Integer id, String name, String phone, Integer amount) {

this.id = id;

this.name = name;

this.phone = phone;

this.amount = amount;

}

public Person(Integer id, String name, String phone) {

this.id = id;

this.name = name;

this.phone = phone;

}

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;

}

@Override

public String toString() {

return "Person [amount=" + amount + ", id=" + id + ", name=" + name

+ ", phone=" + phone + "]";

}



}

7、

package cn.itcast.service;

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

public class DBOpenHelper extends SQLiteOpenHelper {

public DBOpenHelper(Context context) {

super(context, "itcast.db", null, 2);

}

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");

}

@Override

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

db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");

db.execSQL("ALTER TABLE person ADD amount integer");

}

}

8、

package cn.itcast.service;

import java.util.ArrayList;

import java.util.List;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import cn.itcast.domain.Person;

public class PersonService {

private DBOpenHelper dbOpenHelper;



public PersonService(Context context){

dbOpenHelper = new DBOpenHelper(context);

}



public void payment(){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.beginTransaction();//开启事务

try{

db.execSQL("update person set amount=amount-10 where personid=?", new Object[]{1});

db.execSQL("update person set amount=amount+10 where personid=?", new Object[]{2});

db.setTransactionSuccessful();//设置事务标志为成功,在结束事务时才会提供事务,否则回滚事务

}finally{

db.endTransaction();//结束事务

}

}



public void save(Person person){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.execSQL("insert into person(name, phone, amount) values(?,?,?)",

new Object[]{person.getName(), person.getPhone(), person.getAmount()});

//db.close();

}



public void update(Person person){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.execSQL("update person set name=?,phone=?, amount=? where personid=?",

new Object[]{person.getName(), person.getPhone(), person.getAmount(), person.getId()});

}



public void delete(Integer id){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.execSQL("delete from person where personid=?", new Object[]{id});

}



public Person find(Integer id){

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("select * from person where personid=?", new String[]{id.toString()});

if(cursor.moveToFirst()){

int personid = cursor.getInt(cursor.getColumnIndex("personid"));

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

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

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

cursor.close();

return new Person(personid, name, phone, amount);

}

return null;

}



public List<Person> getScrollData(int offset, int maxResult){

List<Person> persons = new ArrayList<Person>();

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("select * from person limit ?,?",

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

while(cursor.moveToNext()){

int personid = cursor.getInt(cursor.getColumnIndex("personid"));

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

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

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

persons.add(new Person(personid, name, phone, amount));

}

return persons;

}



public Cursor getCursorScrollData(int offset, int maxResult){

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

return db.rawQuery("select personid as _id,name,phone,amount from person limit ?,?",

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

}



public long getCount(){

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.rawQuery("select count(*) from person", null);

cursor.moveToFirst();

return cursor.getLong(0);

}

}

9、

package cn.itcast.service;

import java.util.ArrayList;

import java.util.List;

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import cn.itcast.domain.Person;

public class OtherPersonService {

private DBOpenHelper dbOpenHelper;



public OtherPersonService(Context context){

dbOpenHelper = new DBOpenHelper(context);

}



public void save(Person person){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", person.getName());

values.put("phone", person.getPhone());

values.put("amount", person.getAmount());

db.insert("person", null, values); // insert into person(personid) values(NULL)

//db.close();

}



public void update(Person person){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", person.getName());

values.put("phone", person.getPhone());

values.put("amount", person.getAmount());

db.update("person", values, "personid=?", new String[]{person.getId().toString()});

}



public void delete(Integer id){

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

db.delete("person", "personid=?", new String[]{id.toString()});

}



public Person find(Integer id){

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.query("person", new String[]{"personid","name","phone"},

"personid=?", new String[]{id.toString()}, null, null, null);

if(cursor.moveToFirst()){

int personid = cursor.getInt(cursor.getColumnIndex("personid"));

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

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

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

cursor.close();

return new Person(personid, name, phone, amount);

}

return null;

}



public List<Person> getScrollData(int offset, int maxResult){

List<Person> persons = new ArrayList<Person>();

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.query("person", null, null, null, null, null, null, offset+ ","+ maxResult);

while(cursor.moveToNext()){

int personid = cursor.getInt(cursor.getColumnIndex("personid"));

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

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

int amount = cursor.getInt(cursor.getColumnIndex("amount"));

persons.add(new Person(personid, name, phone, amount));

}

return persons;

}



public long getCount(){

SQLiteDatabase db = dbOpenHelper.getReadableDatabase();

Cursor cursor = db.query("person", new String[]{"count(*)"} , null, null, null, null, null);

cursor.moveToFirst();

return cursor.getLong(0);

}

}

10、

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="horizontal"

android:layout_width="fill_parent"

android:layout_height="wrap_content">



<TextView

android:layout_width="100dip"

android:layout_height="wrap_content"

android:text="姓名"

android:id="@+id/name"

/>



<TextView

android:layout_width="100dip"

android:layout_height="wrap_content"

android:text="电话"

android:id="@+id/phone"

/>



<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="存款"

android:id="@+id/amount"

/>

</LinearLayout>

11、

<?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"

>



<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="往内容提供者添加数据"

android:id="@+id/button"

/>





<LinearLayout

android:orientation="horizontal"

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="fill_parent"

android:layout_height="wrap_content"

android:text="存款"

/>

</LinearLayout>

<ListView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:id="@+id/listView"

/>

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