黑马程序员_android笔记3

来源:互联网 发布:游戏设计软件下载 编辑:程序博客网 时间:2024/06/15 02:25

---------------------- android培训、java培训、期待与您交流! ----------------------



第三天    

1、为了实现对数据库版本进行管理,SQLiteOpenHelper类提供了两个重要的方法,分别是onCreate(SQLiteDatabase db)onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion),前者用于初次使用软件时生成数据库表,后者用于升级软件时更新数据库表结构。当调用SQLiteOpenHelpergetWritableDatabase()或者getReadableDatabase()方法获取用于操作数据库的SQLiteDatabase实例的时候,如果数据库不存在,Android系统会自动生成一个数据库,接着调用onCreate()方法,onCreate()方法在初次生成数据库时才会被调用,在onCreate()方法里可以生成数据库表结构及添加一些应用使用到的初始化数据。onUpgrade()方法在数据库的版本发生变化时会被调用,一般在软件升级时才需改变版本号,而数据库的版本是由程序员控制的,假设数据库现在的版本是1,由于业务的变更,修改了数据库表结构,这时候就需要升级软件,升级软件时希望更新用户手机里的数据库表结构,为了实现这一目的,可以把原来的数据库版本设置为2(有同学问设置为3行不行?当然可以,如果你愿意,设置为100也行),并且在onUpgrade()方法里面实现表结构的更新。当软件的版本升级次数比较多,这时在onUpgrade()方法里面可以根据原版号和目标版本号进行判断,然后作出相应的表结构及数据更新。

getWritableDatabase()getReadableDatabase()方法都可以获取一个用于操作数据库的SQLiteDatabase实例。但getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。getReadableDatabase()方法先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。

数据库创建:

import android.content.Context;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

…………

public class PersonDBCreate extends SQLiteOpenHelper {

public PersonDBCreate(Context context) {

super(context, "personDB.db"null, 1); }

public void onCreate(SQLiteDatabase db) {

db.execSQL("create table if not exists person_table  ("

"id integer primary key autoincrement,name varchar(10),age int)"); }

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

数据库操作:

import java.util.ArrayList;

import java.util.List;

import cn.lx.bean.Person;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

public class PersonDBOperate {

private SQLiteDatabase db;

public PersonDBOperate(SQLiteDatabase db) {

this.db = db; }

public void insert(List<Person> persons) {

for (Person p : persons) {

db.execSQL("insert into person_table(name,age) values (?,?)",

new Object[] { p.getName(), p.getAge() }); } }

public void delete(int id) {

db.execSQL("delete from person_table where id=?"new Integer[] { id }); }

public void update(Person person) {

db.execSQL(

"update  person_table set name=?,age=? where id=?",

new Object[] { person.getName(), person.getAge(),

person.getId() }); }

public Person find(int id) {

Person p = new Person();

Cursor c = db.rawQuery("select * from person_table where id=?",

new String[] { id + "" });

if (c.moveToFirst()) {

p.setId(id);

p.setName(c.getString(c.getColumnIndex("name")));

p.setAge(c.getInt(c.getColumnIndex("age"))); }

return p; }

public int getCount() {

Cursor c = db.rawQuery("select count(*) from person_table"null);

c.moveToFirst();

return c.getInt(0); }

public List<Person> getPersons() {

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

Person p = null;

Cursor c = db.rawQuery("select * from person_table"null);

c.moveToFirst();

for (int i = 0; i < c.getCount(); i++) {

p = new Person();

p.setId(c.getInt(c.getColumnIndex("id")));

p.setAge(c.getInt(c.getColumnIndex("age")));

p.setName(c.getString(c.getColumnIndex("name")));

persons.add(p);

p = null;

c.moveToNext(); }

return persons; }}

数据库操作方法测试:

import android.database.sqlite.SQLiteDatabase;

import android.test.AndroidTestCase;

import android.util.Log;

…………

public class TestPersonDBOperate extends AndroidTestCase {

PersonDBCreate pC = null;

SQLiteDatabase db = null;

PersonDBOperate po = null;

public void insertTest() {

pC = new PersonDBCreate(getContext());

db = pC.getWritableDatabase();

po = new PersonDBOperate(db);

List<Person> persons = null;

Person p = null;

persons = new ArrayList<Person>();

for (int i = 0; i < 10; i++) {

p = new Person();

p.setAge(20+i);

p.setName("name" + i);

p.setId(i);

persons.add(p);

p = null; }

po.insert(persons); }

………………

}

使用SQLiteDatabase自带方法操作数据库

delete(String table, String whereClause, String[] whereArgs)

insert(String table, String nullColumnHack, ContentValues values)

query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) 

update(String table,ContentValues values,String whereClause, String[] whereArgs)

2事务操作:

使用SQLiteDatabasebeginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果程序执行到endTransaction()之前调用了setTransactionSuccessful() 方法设置事务的标志为成功则提交事务,如果没有调用setTransactionSuccessful() 方法则回滚事务。使用例子如下:
 SQLiteDatabase db = ....;

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

try {

    db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"传智播客", 4});

    db.execSQL("update person set name=? where personid=?", new Object[]{"传智", 1});

    db.setTransactionSuccessful();//调用此方法会在执行到endTransaction() 时提交当前事务,如果不调用此方法会回滚事务

} finally {

    db.endTransaction();//由事务的标志决定是提交事务,还是回滚事务

db.close(); 

上面两条SQL语句在同一个事务中执行。

3ListView用法(形如android系统设置界面)

1)、先定义每一项(item)的显示布局,通常用TextView控件布局。

item.xml

<?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="80dip"

  android:layout_height="wrap_content"

  android:text="435"

  android:id="@+id/id"

  />

 <TextView

  android:layout_width="100dip"

  android:layout_height="wrap_content"

   android:text="liming"

  android:id="@+id/name"

  />   

<TextView

  android:layout_width="fill_parent"

  android:layout_height="wrap_content"

   android:text="45"

  android:id="@+id/amount"

  />   

</LinearLayout>

2)、在主界面布局文件中修改控件:main.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"

    >

<ListView  

    android:layout_width="fill_parent" 

    android:layout_height="fill_parent" 

    android:id="@+id/listView"

    />

</LinearLayout>

3)、从数据源获取数据,使用适配器把它绑定到ListView中,并且为每项数据指定item界面。

//假设从数据库中获得的字段为id、name、amount的数据

List<Person> persons = personService.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("id", person.getId());

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

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

         data.add(item);

        }

//SimpleAdapter(Context context, List<? extends Map<String,?>> data, int resource, String[] from, int[] to)

        SimpleAdapter adapter = 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(adapter);

备注:可以在ListView标签上加item布局以使之与每一个选项对应的字段说明。形成如下

显示效果:

4)、为点击的item增加点击事件(在以上代码中加入下面的代码):

//单击时显示数据的id

listView.setOnItemClickListener(new OnItemClickListener() {

//onItemClick(AdapterView<?> parent, View view, int position, long id) 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);

Toast.makeText(MainActivity.this, item.get("id").toString(), 1).show();

}

});

5)、假如要绑定的数据是Cursor,也可以使用以下适配器绑定数据:

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

        SimpleCursorAdapter adapter = 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(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {    //注意与前面的方法对比

ListView lView = (ListView)parent;

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

int personid = data.getInt(data.getColumnIndex("_id"));

Toast.makeText(MainActivity.this, personid+"", 1).show();

} });

注:当使用这个适配器是,要求cursor中必须有字段__id(一般_id为主键名),此时,在查询时,可以重命名某个字段。





---------------------- android培训、java培训、期待与您交流! ----------------------

详细请查看:http://edu.csdn.net/heima

原创粉丝点击