- 浏览: 149550 次
- 性别:
- 来自: 五指山
文章分类
最新评论
-
dengdonglin888:
qq_30221445 写道你好 请问这种数据能解吗 < ...
Simple XML -
qq_30221445:
你好 请问这种数据能解吗 <request> ...
Simple XML -
画个逗号给明天qu:
画个逗号给明天qu 写道
Android上传文件到服务器 -
画个逗号给明天qu:
...
Android上传文件到服务器 -
alranger:
我在jsp页面加上这一段代码后,问题还是存在。
解决Ext在ie9报错:不支持extjs对象的“createContextualFragment属性或方法”
转自:http://justsee.iteye.com/blog/932591
除了可以使用文件或SharedPreferences存储数据,还可以选择使用SQLite数据库存储数据。
在Android平台上,集成了一个嵌入式关系型数据库—SQLite,
1、SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型虽然只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。
2、SQLite最大的特点是你可以保存任何类型的数据到任何字段中,无论这列声明的数据类型是什么。例如:可以在Integer字段中存放字符串,或者在布尔型字段中存放浮点数,或者在字符型字段中存放日期型值。
3、但有一种情况例外:定义为INTEGER PRIMARY KEY的字段只能存储64位整数, 当向这种字段中保存除整数以外的数据时,将会产生错误。
4、另外, SQLite 在解析CREATE TABLE 语句时,会忽略 CREATE TABLE 语句中跟在字段名后面的数据类型信息,如下面语句会忽略 name字段的类型信息:
CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))
SQLite可以解析大部分标准SQL语句,如:
查询语句:select * from 表名 where 条件子句 group by 分组字句 having ... order by 排序子句
如:select * from person
select * from person order by id desc
select name from person group by name having count(*)>1
分页SQL与mysql类似,下面SQL语句获取5条记录,跳过前面3条记录
select * from Account limit 5 offset 3 或者 select * from Account limit 3,5
插入语句:insert into 表名(字段列表) values(值列表)。如: insert into person(name, age) values(‘传智’,3)
更新语句:update 表名 set 字段名=值 where 条件子句。如:update person set name=‘传智‘ where id=10
删除语句:delete from 表名 where 条件子句。如:delete from person where id=10
1.创建Android工程
Project name: db
BuildTarget:Android2.2
Application name: 数据库应用
Package name: com.jbridge.db
Create Activity: DBActivity
Min SDK Version:8、
2. Person实体
- package com.jbridge.domain;
- import android.R.string;
- public class Person {
- private Integer id;
- private String name;
- private Short age;
- public Person(String name, Short age) {
- this.name = name;
- this.age = age;
- }
- public Person(Integer id, String name, Short age) {
- super();
- this.id = id;
- this.name = name;
- this.age = age;
- }
- 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 Short getAge() {
- return age;
- }
- public void setAge(Short age) {
- this.age = age;
- }
- @Override
- public String toString() {
- return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
- }
- }
package com.jbridge.domain; import android.R.string; public class Person { private Integer id; private String name; private Short age; public Person(String name, Short age) { this.name = name; this.age = age; } public Person(Integer id, String name, Short age) { super(); this.id = id; this.name = name; this.age = age; } 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 Short getAge() { return age; } public void setAge(Short age) { this.age = age; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + "]"; } }
3.编写DataBaseOpenHelper类
DataBaseOpenHelper继承自SQLiteOpenHelper类。我们需要创建数据表,必须重写onCreate(更新时重写onUpgrade方法)方法,在这个方法中创建数据表。
- package com.jbridge.service;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DataBaseOpenHelper extends SQLiteOpenHelper {
- // 类没有实例化,是不能用作父类构造器的参数,必须声明为静态
- private static String dbname = "zyj";
- private static int version = 1;
- public DataBaseOpenHelper(Context context) {
- // 第一个参数是应用的上下文
- // 第二个参数是应用的数据库名字
- // 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类
- // 第四个参数是数据库版本,必须是大于0的int(即非负数)
- super(context, dbname, null, version);
- // TODO Auto-generated constructor stub
- }
- public DataBaseOpenHelper(Context context, String name,
- CursorFactory factory, int version) {
- super(context, name, factory, version);
- // TODO Auto-generated constructor stub
- }
- @Override
- public void onCreate(SQLiteDatabase db) {
- db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)");
- }
- // onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。
- // 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。
- @Override
- public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
- db.execSQL("DROP TABLE IF EXISTS person");
- onCreate(db);
- }
- }
package com.jbridge.service; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DataBaseOpenHelper extends SQLiteOpenHelper { // 类没有实例化,是不能用作父类构造器的参数,必须声明为静态 private static String dbname = "zyj"; private static int version = 1; public DataBaseOpenHelper(Context context) { // 第一个参数是应用的上下文 // 第二个参数是应用的数据库名字 // 第三个参数CursorFactory指定在执行查询时获得一个游标实例的工厂类,设置为null,代表使用系统默认的工厂类 // 第四个参数是数据库版本,必须是大于0的int(即非负数) super(context, dbname, null, version); // TODO Auto-generated constructor stub } public DataBaseOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name varchar(20), age INTEGER)"); } // onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。 // 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。 @Override public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) { db.execSQL("DROP TABLE IF EXISTS person"); onCreate(db); } }4.编写PersonService类
PersonService类主要实现对业务逻辑和数据库的操作。
- package com.jbridge.service;
- import java.util.ArrayList;
- import java.util.Currency;
- import java.util.List;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import com.jbridge.domain.Person;
- public class PersonService {
- private DataBaseOpenHelper dbOpenHelper;
- // private Context context;
- public PersonService(Context context) {
- // this.context = context;
- dbOpenHelper = new DataBaseOpenHelper(context);
- }
- public void save(Person person) {
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- database.beginTransaction();
- database.execSQL("insert into person(name,age)values(?,?)",
- new Object[] { person.getName(), person.getAge() });
- // database.close();可以不关闭数据库,他里面会缓存一个数据库对象,如果以后还要用就直接用这个缓存的数据库对象。但通过
- // context.openOrCreateDatabase(arg0, arg1, arg2)打开的数据库必须得关闭
- database.setTransactionSuccessful();
- database.endTransaction();
- }
- public void update(Person person) {
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- database.execSQL(
- "update person set name=?,age=? where personid=?",
- new Object[] { person.getName(), person.getAge(),
- person.getId() });
- }
- public Person find(Integer id) {
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.rawQuery(
- "select * from person where personid=?",
- new String[] { String.valueOf(id) });
- if (cursor.moveToNext()) {
- return new Person(cursor.getInt(0), cursor.getString(1),
- cursor.getShort(2));
- }
- return null;
- }
- public void delete(Integer... ids) {
- if (ids.length > 0) {
- StringBuffer sb = new StringBuffer();
- for (Integer id : ids) {
- sb.append('?').append(',');
- }
- sb.deleteCharAt(sb.length() - 1);
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- database.execSQL(
- "delete from person where personid in(" + sb.toString()
- + ")", ids);
- }
- }
- public List<Person> getScrollData(int startResult, int maxResult) {
- List<Person> persons = new ArrayList<Person>();
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.rawQuery(
- "select * from person limit ?,?",
- new String[] { String.valueOf(startResult),
- String.valueOf(maxResult) });
- while (cursor.moveToNext()) {
- persons.add(new Person(cursor.getInt(0), cursor.getString(1),
- cursor.getShort(2)));
- }
- return persons;
- }
- // 获取分页数据,提供给SimpleCursorAdapter使用。
- public Cursor getRawScrollData(int startResult, int maxResult) {
- List<Person> persons = new ArrayList<Person>();
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- return database.rawQuery(
- "select personid as _id ,name,age from person limit ?,?",
- new String[] { String.valueOf(startResult),
- String.valueOf(maxResult) });
- }
- public long getCount() {
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.rawQuery("select count(*) from person", null);
- if (cursor.moveToNext()) {
- return cursor.getLong(0);
- }
- return 0;
- }
- }
package com.jbridge.service; import java.util.ArrayList; import java.util.Currency; import java.util.List; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.jbridge.domain.Person; public class PersonService { private DataBaseOpenHelper dbOpenHelper; // private Context context; public PersonService(Context context) { // this.context = context; dbOpenHelper = new DataBaseOpenHelper(context); } public void save(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.beginTransaction(); database.execSQL("insert into person(name,age)values(?,?)", new Object[] { person.getName(), person.getAge() }); // database.close();可以不关闭数据库,他里面会缓存一个数据库对象,如果以后还要用就直接用这个缓存的数据库对象。但通过 // context.openOrCreateDatabase(arg0, arg1, arg2)打开的数据库必须得关闭 database.setTransactionSuccessful(); database.endTransaction(); } public void update(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.execSQL( "update person set name=?,age=? where personid=?", new Object[] { person.getName(), person.getAge(), person.getId() }); } public Person find(Integer id) { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery( "select * from person where personid=?", new String[] { String.valueOf(id) }); if (cursor.moveToNext()) { return new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2)); } return null; } public void delete(Integer... ids) { if (ids.length > 0) { StringBuffer sb = new StringBuffer(); for (Integer id : ids) { sb.append('?').append(','); } sb.deleteCharAt(sb.length() - 1); SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.execSQL( "delete from person where personid in(" + sb.toString() + ")", ids); } } public List<Person> getScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery( "select * from person limit ?,?", new String[] { String.valueOf(startResult), String.valueOf(maxResult) }); while (cursor.moveToNext()) { persons.add(new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2))); } return persons; } // 获取分页数据,提供给SimpleCursorAdapter使用。 public Cursor getRawScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); return database.rawQuery( "select personid as _id ,name,age from person limit ?,?", new String[] { String.valueOf(startResult), String.valueOf(maxResult) }); } public long getCount() { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.rawQuery("select count(*) from person", null); if (cursor.moveToNext()) { return cursor.getLong(0); } return 0; } }
下面是使用 insert()、delete()、update()和query()方法实现的业务类
- package com.jbridge.service;
- import java.util.ArrayList;
- import java.util.Currency;
- import java.util.List;
- import android.R.string;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import com.jbridge.domain.Person;
- public class OtherPersonService {
- private DataBaseOpenHelper dbOpenHelper;
- // private Context context;
- public OtherPersonService(Context context) {
- // this.context = context;
- dbOpenHelper = new DataBaseOpenHelper(context);
- }
- public void save(Person person) {
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("name", person.getName());
- contentValues.put("age", person.getAge());
- database.insert("person", null, contentValues);
- }
- public void update(Person person) {
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- ContentValues contentValues = new ContentValues();
- contentValues.put("name", person.getName());
- contentValues.put("age", person.getAge());
- database.update("person", null, "personid=?",
- new String[] { String.valueOf(person.getId()) });
- }
- public Person find(Integer id) {
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.query("person", new String[] { "personid",
- "name", "age" }, "personid=?",
- new String[] { String.valueOf(id) }, null, null, null);
- if (cursor.moveToNext()) {
- return new Person(cursor.getInt(0), cursor.getString(1),
- cursor.getShort(2));
- }
- return null;
- }
- public void delete(Integer... ids) {
- if (ids.length > 0) {
- StringBuffer sb = new StringBuffer();
- String[] strIds = new String[ids.length];
- // for (Integer id : ids) {
- // sb.append('?').append(',');
- // }
- for (int i = 0; i < strIds.length; i++) {
- sb.append('?').append(',');
- strIds[i] = String.valueOf(ids[i]);
- }
- sb.deleteCharAt(sb.length() - 1);
- SQLiteDatabase database = dbOpenHelper.getWritableDatabase();
- database.delete("person", "personid in(" + sb.toString() + ")",
- strIds);
- }
- }
- public List<Person> getScrollData(int startResult, int maxResult) {
- List<Person> persons = new ArrayList<Person>();
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.query("person", new String[] { "personid",
- "name", "age" }, null, null, null, null, "personid desc",
- startResult + "," + maxResult);
- while (cursor.moveToNext()) {
- persons.add(new Person(cursor.getInt(0), cursor.getString(1),
- cursor.getShort(2)));
- }
- return persons;
- }
- public long getCount() {
- SQLiteDatabase database = dbOpenHelper.getReadableDatabase();
- Cursor cursor = database.query("person", new String[] { "count(*)" },
- null, null, null, null, null);
- if (cursor.moveToNext()) {
- return cursor.getLong(0);
- }
- return 0;
- }
- }
package com.jbridge.service; import java.util.ArrayList; import java.util.Currency; import java.util.List; import android.R.string; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.jbridge.domain.Person; public class OtherPersonService { private DataBaseOpenHelper dbOpenHelper; // private Context context; public OtherPersonService(Context context) { // this.context = context; dbOpenHelper = new DataBaseOpenHelper(context); } public void save(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); database.insert("person", null, contentValues); } public void update(Person person) { SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", person.getName()); contentValues.put("age", person.getAge()); database.update("person", null, "personid=?", new String[] { String.valueOf(person.getId()) }); } public Person find(Integer id) { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "personid", "name", "age" }, "personid=?", new String[] { String.valueOf(id) }, null, null, null); if (cursor.moveToNext()) { return new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2)); } return null; } public void delete(Integer... ids) { if (ids.length > 0) { StringBuffer sb = new StringBuffer(); String[] strIds = new String[ids.length]; // for (Integer id : ids) { // sb.append('?').append(','); // } for (int i = 0; i < strIds.length; i++) { sb.append('?').append(','); strIds[i] = String.valueOf(ids[i]); } sb.deleteCharAt(sb.length() - 1); SQLiteDatabase database = dbOpenHelper.getWritableDatabase(); database.delete("person", "personid in(" + sb.toString() + ")", strIds); } } public List<Person> getScrollData(int startResult, int maxResult) { List<Person> persons = new ArrayList<Person>(); SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "personid", "name", "age" }, null, null, null, null, "personid desc", startResult + "," + maxResult); while (cursor.moveToNext()) { persons.add(new Person(cursor.getInt(0), cursor.getString(1), cursor.getShort(2))); } return persons; } public long getCount() { SQLiteDatabase database = dbOpenHelper.getReadableDatabase(); Cursor cursor = database.query("person", new String[] { "count(*)" }, null, null, null, null, null); if (cursor.moveToNext()) { return cursor.getLong(0); } return 0; } }5.编写测试类
编写一个针对PersonService的测试类,测试PersonService类中的各个方法是否正确。
- package com.jbridge.db;
- import java.util.List;
- import com.jbridge.domain.Person;
- import com.jbridge.service.OtherPersonService;
- import com.jbridge.service.PersonService;
- import android.test.AndroidTestCase;
- import android.util.Log;
- public class PersonServiceTest extends AndroidTestCase {
- private static String TAG = "PersonServiceTest";
- // OtherPersonService personService = new
- // OtherPersonService(this.getContext());
- // //不可以这么写,因为Android把context环境变量是在PersonServiceTest实例化后给他的
- public void testSave() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- // personService.save(new Person("老猪", (short) 11));
- for (int i = 0; i < 10; i++) {
- personService.save(new Person("你" + i, (short) (i + 10)));
- }
- }
- public void testFind() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- Person person = personService.find(1);
- Log.i(TAG, person.toString());
- }
- public void testUpdate() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- Person person = personService.find(1);
- person.setName("lv");
- personService.update(person);
- }
- public void testDelete() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- personService.delete(1, 2, 3);
- }
- public void testGetCount() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- Log.i(TAG, String.valueOf(personService.getCount()));
- }
- public void testGetScrollData() throws Exception {
- PersonService personService = new PersonService(this.getContext());
- List<Person> persons = personService.getScrollData(0, 3);
- for (Person person : persons) {
- Log.i(TAG, person.toString());
- }
- }
- }
package com.jbridge.db; import java.util.List; import com.jbridge.domain.Person; import com.jbridge.service.OtherPersonService; import com.jbridge.service.PersonService; import android.test.AndroidTestCase; import android.util.Log; public class PersonServiceTest extends AndroidTestCase { private static String TAG = "PersonServiceTest"; // OtherPersonService personService = new // OtherPersonService(this.getContext()); // //不可以这么写,因为Android把context环境变量是在PersonServiceTest实例化后给他的 public void testSave() throws Exception { PersonService personService = new PersonService(this.getContext()); // personService.save(new Person("老猪", (short) 11)); for (int i = 0; i < 10; i++) { personService.save(new Person("你" + i, (short) (i + 10))); } } public void testFind() throws Exception { PersonService personService = new PersonService(this.getContext()); Person person = personService.find(1); Log.i(TAG, person.toString()); } public void testUpdate() throws Exception { PersonService personService = new PersonService(this.getContext()); Person person = personService.find(1); person.setName("lv"); personService.update(person); } public void testDelete() throws Exception { PersonService personService = new PersonService(this.getContext()); personService.delete(1, 2, 3); } public void testGetCount() throws Exception { PersonService personService = new PersonService(this.getContext()); Log.i(TAG, String.valueOf(personService.getCount())); } public void testGetScrollData() throws Exception { PersonService personService = new PersonService(this.getContext()); List<Person> persons = personService.getScrollData(0, 3); for (Person person : persons) { Log.i(TAG, person.toString()); } } }启用测试功能,不要忘记在AndroidManifest.xml文件中加入测试环境。为application元素添加一个子元素:<uses-library android:name="android.test.runner"/>,为application元素添加一个兄弟元素:<instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.jbridge.db" android:label="Tests for My App" />。
SQLite数据库以单个文件存储,就像微软的Access数据库。有一个查看SQLite数据库文件的工具——SQLite Developer,我们可以使用它来查看数据库。Android将创建的数据库存放在”/data/data/ com.jbridge.db/databases/person”,我们将它导出然后使用SQLite Developer打开。
6.分页显示数据
我们在ContactsService类中,提供了一个获取分页数据的方法。我们将调用它获取的数据,使用ListView组件显示出来。
编辑mail.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="40px"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:id="@+id/personidtitle"
- android:text="编号"
- />
- <TextView
- android:layout_width="200px"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:layout_toRightOf="@id/personidtitle"
- android:layout_alignTop="@id/personidtitle"
- android:gravity="center_horizontal"
- android:id="@+id/nametitle"
- android:text="姓名"
- />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:layout_toRightOf="@id/nametitle"
- android:layout_alignTop="@id/nametitle"
- android:id="@+id/agetitle"
- android:text="年龄"
- />
- </RelativeLayout>
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/listView"
- />
- </LinearLayout>
<?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="40px" android:layout_height="wrap_content" android:textSize="20px" android:id="@+id/personidtitle" android:text="编号" /> <TextView android:layout_width="200px" android:layout_height="wrap_content" android:textSize="20px" android:layout_toRightOf="@id/personidtitle" android:layout_alignTop="@id/personidtitle" android:gravity="center_horizontal" android:id="@+id/nametitle" android:text="姓名" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20px" android:layout_toRightOf="@id/nametitle" android:layout_alignTop="@id/nametitle" android:id="@+id/agetitle" android:text="年龄" /> </RelativeLayout> <ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/listView" /> </LinearLayout>
在mail.xml所在目录里添加一个personitem.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="40px"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:id="@+id/personid"
- />
- <TextView
- android:layout_width="200px"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:layout_toRightOf="@id/personid"
- android:layout_alignTop="@id/personid"
- android:gravity="center_horizontal"
- android:id="@+id/name"
- />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="20px"
- android:layout_toRightOf="@id/name"
- android:layout_alignTop="@id/name"
- android:id="@+id/age"
- />
- </RelativeLayout>
<?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="40px" android:layout_height="wrap_content" android:textSize="20px" android:id="@+id/personid" /> <TextView android:layout_width="200px" android:layout_height="wrap_content" android:textSize="20px" android:layout_toRightOf="@id/personid" android:layout_alignTop="@id/personid" android:gravity="center_horizontal" android:id="@+id/name" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20px" android:layout_toRightOf="@id/name" android:layout_alignTop="@id/name" android:id="@+id/age" /> </RelativeLayout>
编辑 DBActivity 类:
- package com.jbridge.db;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import com.jbridge.domain.Person;
- import com.jbridge.service.PersonService;
- import android.R.string;
- import android.app.Activity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.provider.LiveFolders;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import android.widget.SimpleAdapter;
- import android.widget.SimpleCursorAdapter;
- import android.widget.Toast;
- public class DBActivity extends Activity {
- /** Called when the activity is first created. */
- private static final String TAG = "DBActivity";
- /*实现方法一
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- PersonService personService=new PersonService(this);
- ListView listView = (ListView) this.findViewById(R.id.listView);
- List<HashMap<String, String>> data = new ArrayList<HashMap<String,
- String>>();
- // HashMap<String, String> title = new HashMap<String, String>();
- // title.put("personid", "编号");
- // title.put("name", "姓名");
- // title.put("age", "年龄");
- // data.add(title);
- List<Person> persons= personService.getScrollData(0, 10);
- for (Person person : persons) {
- HashMap<String, String> p = new HashMap<String, String>();
- p.put("personid", String.valueOf(person.getId()));
- p.put("name", person.getName());
- p.put("age",String.valueOf(person.getAge()));
- data.add(p);
- }
- // 适配器有:
- // ArrayAdapter<T>
- // simpAdapter
- // SimpleCursorAdapter
- SimpleAdapter adapter = new SimpleAdapter(DBActivity.this, data,
- R.layout.personitem,
- new String[] { "personid", "name", "age" },
- new int[] {R.id.personid, R.id.name, R.id.age });
- listView.setAdapter(adapter);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
- @Override
- // parent即为你点击的listView
- // view为listview的外面布局
- public void onItemClick(AdapterView<?> parent, View view, int position,
- long id) {
- ListView listView= (ListView) parent;
- HashMap<String, String> itemdata= (HashMap<String, String>)
- listView.getItemAtPosition(position);
- String personid=itemdata.get("personid");
- String name=itemdata.get("name");
- String age=itemdata.get("age");
- Log.i(TAG,view.getClass().getName());
- Log.i(TAG, "personid: "+personid+ " name: "+name+" age: "+age);
- Log.i(TAG," position==id:"+ (position==id));
- Toast.makeText(DBActivity.this, name, Toast.LENGTH_LONG).show();
- }
- });
- }
- */
- // 实现方法二(游标)
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- PersonService personService = new PersonService(this);
- ListView listView = (ListView) this.findViewById(R.id.listView);
- List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
- // HashMap<String, String> title = new HashMap<String, String>();
- // title.put("personid", "编号");
- // title.put("name", "姓名");
- // title.put("age", "年龄");
- // data.add(title);
- // 适配器有:
- // ArrayAdapter<T>
- // simpAdapter
- // SimpleCursorAdapter
- Cursor cursor = personService.getRawScrollData(0, 10);
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(DBActivity.this,
- R.layout.personitem, cursor, new String[] { "_id", "name",
- "age" },
- new int[] { R.id.personid, R.id.name, R.id.age });
- listView.setAdapter(adapter);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- // parent即为你点击的listView
- // view为listview的外面布局
- public void onItemClick(AdapterView<?> parent, View view,
- int position, long id) {
- ListView listView = (ListView) parent;
- Cursor cursor = (Cursor) listView.getItemAtPosition(position);
- String personid = String.valueOf(cursor.getInt(0));
- String name = String.valueOf(cursor.getString(1));
- String age = String.valueOf(cursor.getShort(2));
- Log.i(TAG, view.getClass().getName());
- Log.i(TAG, "personid: " + personid + " name: " + name
- + " age: " + age);
- Log.i(TAG, " position==id:" + (position == id));
- Toast.makeText(DBActivity.this, name, Toast.LENGTH_LONG).show();
- }
- });
- }
- }
发表评论
-
xUtils简介
2014-11-25 10:04 841xUtils 包含了很多实用的android工具。 xU ... -
直接拿来用!最火的Android开源项目
2014-07-25 11:01 698转 http://www.admin10000.com/d ... -
Android APK反编译详解(附图)
2014-03-28 10:56 814http://blog.csdn.net/ithomer/ar ... -
小米人
2014-02-17 17:23 681http://www.xiaomiren.net/ -
android开发之gallery 兑现滚动一张且短距离滑动实现滚动
2013-07-02 15:28 659http://www.myexception.cn/andro ... -
TextView显示插入的图片
2013-07-01 11:29 696http://orgcent.com/android-text ... -
TextView使用SpannableString设置复合文本
2013-07-01 11:29 640http://orgcent.com/android-text ... -
转:::Android TextView文字横向自动滚动(跑马灯)
2013-06-17 11:45 1507TextView实现文字滚动需要以下几个要点: 1.文字长度长 ... -
相片滤镜开源
2013-04-27 15:01 730https://github.com/daizhenjun/I ... -
android图片特效处理之模糊效果
2013-04-27 14:57 826http://blog.csdn.net/sjf0115/ar ... -
android图片处理方法(不断收集中)
2013-04-27 14:57 552http://gundumw100.iteye.com/blo ... -
Android, WindowsPhone7, IOS ,vc2010平台40多套图片滤镜开源
2013-04-27 14:56 658http://www.cnblogs.com/daizhj/a ... -
移动云存储平台
2013-04-25 16:13 903http://bmob.cn 关于Bmob 对于很多 ... -
android ExpandableListView简单应用及listview模拟ExpandableListView
2013-02-28 11:45 688http://blog.csdn.net/jj120522/a ... -
android_App集成支付宝
2013-02-28 11:43 782http://www.cnblogs.com/qianxude ... -
Android Pull Refresh View 插件
2012-12-01 12:43 843Android Pull Refresh View htt ... -
Android-TelephoneManager(转载)
2012-10-09 22:08 1343好文章齐分享。原文地址:http://blog.si ... -
android 开源 listview separato
2012-08-27 22:51 660http://code.google.com/p/androi ... -
fragment开源项目 学习
2012-08-13 12:02 928https://github.com/tisa007/Andr ... -
Fragment学习
2012-08-13 11:53 665http://www.eoeandroid.com/threa ...
相关推荐
本文实例分析了Android编程操作嵌入式关系型SQLite数据库的方法。分享给大家供大家参考,具体如下: SQLite特点 1.Android平台中嵌入了一个关系型数据库SQLite,和其他数据库不同的是SQLite存储数据时不区分类型 ...
一、使用嵌入式关系型SQLite数据库存储数据 在Android平台上,集成了一个嵌入式关系型数据库——SQLite,SQLite3支持NULL、INTEGER、REAL(浮点数字)、 TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的...
SQLite是目前最流行的开源嵌入式数据库,和很多其他嵌入式存储引擎相比(NoSQL),如BerkeleyDB、MemBASE等,SQLite可以很好的支持关系型数据库所具备的一些基本特征,如标准SQL语法、事务、数据表和索引等。...
SQLite是一个轻量级的关系型数据库管理系统,遵守ACID原则,其特点是高度便携、使用方便、结构紧凑、高效和可靠。它不是客户端-服务器结构的数据库,而是嵌入式的数据库引擎,可以将其看作是一个单一的、自包含的、...
作为嵌入式关系型数据库管理系统,它提供了有效的数据存储和管理方式。在Linux环境中,SQLite3无需额外的数据库服务器即可被嵌入到应用程序中,从而简化了应用的部署和维护。SQLite3不仅支持多种数据类型和SQL查询...
最近有WPF做客户端,需要离线操作存储数据,在项目中考虑使用Sqlite嵌入式数据库,在网上找了不少资料,最终整理出一个公共的帮助类。 Sqlite是一个非常小巧的数据库,基本上具备关系型数据库操作的大多数功能,Sql...
SQLite是一种轻量级的、嵌入式的关系型数据库管理系统(RDBMS),它以库的形式被嵌入到应用程序中,而不是作为独立的服务器运行。SQLite的设计目标是尽可能简单、轻量、快速,并且易于集成到各种编程语言中。 以下...
于C/S 或B/S 结构的关系型数据库来实现数据的存储、检索等功能。然而,在嵌入式系统中, 由于软硬件资源有限,不可能安装庞大的数据库服务器,而用户的需求可能由一个简单的基 于磁盘文件的数据库系统就能实现,这...
嵌入式Android项目设计与开发 第六章 数据存储 ——SQLite 2 SQLite 数据库管理员 数据库实体A 表 表 数据库实体B 表 表 数据库实体 表 表 SQLite 我们已经掌握: SQLite是一款轻量级的关系型数据库,它的运算效率高...
它的设计目标是嵌入式的,而且占用资源非常低,在内存中只需要占用几百kB的存储空间,这也是Android移动设备采用SQLite数据库的重要原因之一。 SQLite 是遵守ACID的关系型数据库管理系统。这里的ACID是指数据库事务...
用 SQLite连接的程序可以使用SQL数据库,但不需要运行一个单独的关系型数据库管理系统进程(separate RDBMS process)。 SQLite不是一个用于连接到大型数据库服务器(big database server)的客户端库(client ...
SQLite是一款开源的、嵌入式关系型数据库,第一个版本Alpha发布于2000年。SQLite在便携性、易用性、紧凑性、高效性和可靠性方面有着突出的表现。 在Android中创建的SQLite数据库存储在:/data/data/<包名>/...
1嵌入式数据库SQLite与传统C/s结构的各种大型关系数据库如Oracle,SQL Server,MySQL等相比,在嵌入式系统中由于软硬件资源有限,不可能安装庞大的数据库服务器,而且在很多时候,用户只需要使用这些数据库产品的一
一、关系型数据库SQLIte 每个应用程序都要使用数据,Android应用程序也不例外,Android使用开源的、与操作系统无关的SQL数据库—SQLite。SQLite第一个Alpha版本诞生于2000年5月,它是一款轻量级数据库,它的设计...
SQLite 是一种嵌入式关系型数据库,其本质就是一个文件,它占用资源低、处理速度快、跨平台、可与 Python、Java 等多种编程语言结合使用。 SQLite 是一个进程内的库,可以自给自足、无服务器、无需配置、支持事务,...
2. SQLite:SQLite是一种嵌入式关系型数据库管理系统,广泛应用于移动设备和嵌入式系统。它是Android应用程序常用的本地数据库解决方案,可用于存储和管理应用程序的数据。 3. 登录注册功能:登录注
摘 要 深入分析、比较Berkeley DB和sQLite。...像MySQL这类基于C/S结构的关系型数据库系统,虽然代表着目前数据库应用的主流,却并不能满足所有应用场合的需要。很多的应用,仅仅利用到了这些数据库产品的基本特
嵌入式Android项目设计与开发 第六章 数据存储 ——SQLite 1 SQLite 概念: SQLite是一款轻量级的关系型数据库,它的运算效率高,占用资源少,因此比较适合在移动设备上使用。 SQLite Android为了让我们更加方便地...
SQLite 是一个开源的嵌入式关系数据库,它可以减少应用程序管理数据的开销 , SQLite 可移植性好 、 很容易使用 、 很小 、 高效而且可靠 。目前在Android 系统中集成的是 SQLite3 版本 ,SQLite 不支持静态数据类型...
像MySQL这类基于C/S结构的关系型数据库系统,虽然代表着目前数据库应用的主流,却并不能满足所有应用场合的需要。很多的应用,仅仅利用到了这些数据库产品的基本特性而已。有时我们需要的可能只是一个简单的基于...