標籤:android sqlite 儲存物件
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>
其中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; }}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
【Android基礎】Android SQLite儲存自訂對象