【Android基础】Android SQLite存储自定义对象

来源:互联网 发布:linux 读音 编辑:程序博客网 时间:2024/06/16 11:35

Android SQLite存储自定义对象

在SQLite数据库中可存储的数据类型有NULL、INTEGER、REAL(浮点型)、TEXT、BOOL,一共是五种数据类型。在Android开发中,我们存储数据的一般的作法是数据库的属性就是类的成员变量,比如:
要存储一个人的姓名和年龄,在类中的是将它们定义为两个成员变量

class Person{    private String name;    private int age;}

数据库中是将它们存储为两个字段
- name TEXT
- age INTEGER

现在我要介绍的这种方法是直接把Persond1实例存储在数据库里,也就是在数据库中存储对象。
具体做法是:将对象序列化为字节流字符串,然后将字节流字符串以TEXT类型存储在数据库中;在取数据时,将字节流反序列化为对象就行了。所以我们的实体类得是实现了Serializable接口的类。

下面是实例(下载):

  • 首先是Person类,这是我们存储的实体类,只有set和get方法,并且实现了序列化接口
package com.databasetest;import java.io.Serializable;@SuppressWarnings("serial")public class Person implements Serializable{    private String name;    private int age;    public Person(){        this("",0);//默认值    }    public Person(String name, int age){        this.name = name;        this.age  = age;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }}
  • 然后是数据库的辅助类
package com.db;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class DBServices extends SQLiteOpenHelper{    public final static int version = 1;    public final static String dbName = "Test";    public DBServices(Context context){        super(context,dbName,null,version);    }    @Override    public void onCreate(SQLiteDatabase db) {        // TODO Auto-generated method stub        db.beginTransaction();        //创建邮件表        String create_mail_sql = "CREATE TABLE if not exists [Test]"+                "(_id integer primary key autoincrement,person text)";        db.execSQL(create_mail_sql);        db.setTransactionSuccessful();        db.endTransaction();    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        // TODO Auto-generated method stub    }}
  • 接下来是实例界面,有两个输入框用来输入姓名和年龄,一个按钮用于确认,还有一个列表显示数据库中存储的信息
    这是layout文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/LinearLayout1"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.databasetest.MainActivity" >    <EditText        android:id="@+id/editText1"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:ems="10"        android:hint="姓名" />    <EditText        android:id="@+id/editText2"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:ems="10"        android:hint="年龄" >        <requestFocus />    </EditText>    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="确定添加" />    <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="vertical" >            <ListView                android:id="@+id/listView1"                android:layout_width="match_parent"                android:layout_height="fill_parent" >            </ListView>        </LinearLayout></LinearLayout>
  • 最后就是MainActivity

其中saveData方法用于存储对象;getAllObject用于获取数据库中所有的Person对象。

public class MainActivity extends ActionBarActivity {    EditText tv1;    EditText tv2;    Button btn;    ListView lv;    ArrayList<String> array = new ArrayList<String>();    ArrayAdapter<String> adapter;    DBServices db = new DBServices(this);    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //获取控件        tv1 = (EditText)findViewById(R.id.editText1);        tv2 = (EditText)findViewById(R.id.editText2);        btn = (Button)findViewById(R.id.button1);        lv  = (ListView)findViewById(R.id.listView1);        //初始化数据库中的数据        initDB();        btn.setOnClickListener(new OnClickListener(){            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                String name = tv1.getText().toString();                String age = tv2.getText().toString();                int nAge = 0;                try{                    nAge = Integer.valueOf(age);                }catch(NumberFormatException exception){                    exception.printStackTrace();                    nAge = 0;                }                Person person = new Person(name,Integer.valueOf(age));                array.add(name+" - "+age);                saveData(person);                lv.invalidateViews();            }        });    }    private void initDB(){        db = new DBServices(this);        ArrayList<Person> persons = this.getAllObject();        for(int i=0;i<persons.size();i++){            String object = persons.get(i).getName()                    + " - "                    + persons.get(i).getAge();            this.array.add(object);        }        adapter = new ArrayAdapter<String>(this,                android.R.layout.simple_expandable_list_item_1,array);        lv.setAdapter(adapter);    }    /**       * 保存数据       * @param student       */      public void saveData(Person person) {        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();        try {          ObjectOutputStream objectOutputStream = new ObjectOutputStream(arrayOutputStream);          objectOutputStream.writeObject(person);          objectOutputStream.flush();          byte data[] = arrayOutputStream.toByteArray();          objectOutputStream.close();          arrayOutputStream.close();          SQLiteDatabase database = db.getWritableDatabase();          database.execSQL("insert into Test (person) values(?)", new Object[] { data });          database.close();        } catch (Exception e) {          // TODO Auto-generated catch block          e.printStackTrace();        }      }      public ArrayList<Person> getAllObject() {          ArrayList<Person> persons = new ArrayList<Person>();          SQLiteDatabase database = db.getReadableDatabase();          Cursor cursor = database.rawQuery("select * from Test", null);          if (cursor != null) {              while (cursor.moveToNext()) {                  Log.d("data-id",cursor.getString(0));                  byte data[] = cursor.getBlob(cursor.getColumnIndex("person"));                  ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(data);                  try {                      ObjectInputStream inputStream = new ObjectInputStream(arrayInputStream);                      Person person = (Person) inputStream.readObject();                      persons.add(person);                      inputStream.close();                      arrayInputStream.close();                  } catch (Exception e) {                      e.printStackTrace();                  }              }         }         Log.d("Persons-Count",Integer.toString(persons.size()));         return persons;      }}
  • 实例代码下载地址
1 0
原创粉丝点击