"Android Basics" Android SQLite store custom objects

Source: Internet
Author: User
Tags sqlite database

Android SQLite Store Custom objects

The data types that can be stored in the SQLite database are null, INTEGER, REAL (floating point), TEXT, BOOL, all five data types. In Android development, the general practice in which we store data is that the properties of the database are the member variables of the class, such as:
To store a person's name and age, in the class is to define them as two member variables

class Person{    private String name;    privateint age;}

They are stored as two fields in a database
-Name TEXT
-Age INTEGER

The way I'm going to introduce this is to store the Persond1 instance directly in the database, that is, to store the object in the database.
This is done by serializing the object into a byte stream string, then storing the byte stream string in the database in the text type, and then deserializing the byte stream into the object when fetching the data. So our entity class is the class that implements the Serializable interface.

Here is an example (download):

    • The first is the person class, which is the entity class we store, only the set and get methods, and the serialization interface is implemented
 PackageCom.databasetest;Importjava.io.Serializable;@SuppressWarnings("Serial") Public  class  person implements Serializable{    PrivateString name;Private intAge Public  Person(){ This("",0);//Default value} Public  Person(String name,intAge) { This. name = name; This. Age = Age; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }}
    • Then the auxiliary class of the database
 Packagecom.db;ImportAndroid.content.ContentValues;ImportAndroid.content.Context;ImportAndroid.database.Cursor;ImportAndroid.database.sqlite.SQLiteDatabase;ImportAndroid.database.sqlite.SQLiteOpenHelper;ImportAndroid.util.Log; Public  class dbservices extends sqliteopenhelper{     Public Final Static intVersion =1; Public Final StaticString DbName ="Test"; Public dbservices(Context context) {Super(Context,dbname,NULL, version); }@Override     Public void onCreate(Sqlitedatabase db) {//TODO auto-generated method stubDb.begintransaction ();//Create a mailing tableString 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,intOldversion,intNewVersion) {//TODO auto-generated method stub}}
    • Next is the instance interface, with two input boxes for name and age, a button for confirmation, and a list showing the information stored in the database
      This is the layout file:
<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  ="  android:hint  = "name" /& gt;     <EditTextandroid:id= "@+id/edittext2"android:layout_width="Fill_ Parent "android:layout_height="wrap_content "android:ems=" Ten "  Android:hint="Age" >                                                <requestfocus />    </EditText>    <buttonandroid:id="@+id/button1"android:layout_width="Wrap_ Content "android:layout_height=" Wrap_content "android:text=" ok add " />                                     <linearlayoutandroid:layout_width="Match_parent"android:layout_ Height="Wrap_content"android:orientation="vertical" >                                                <ListViewandroid:id="@+id/listview1"android:layout_width="Match _parent "android:layout_height=" Fill_parent " >                                                            </ListView>        </linearlayout></linearlayout>
    • The last is mainactivity.

Where the SaveData method is used to store the object; Getallobject is used to get all the person objects in the database.

 Public  class mainactivity extends actionbaractivity {EditText TV1;    EditText TV2;    Button btn;    ListView LV; arraylist<string> array =NewArraylist<string> ();    Arrayadapter<string> adapter; Dbservices db =NewDbservices ( This);@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main);//Get controlTV1 = (EditText) Findviewbyid (R.ID.EDITTEXT1);        TV2 = (EditText) Findviewbyid (R.ID.EDITTEXT2);        BTN = (Button) Findviewbyid (R.id.button1); LV = (ListView) Findviewbyid (R.ID.LISTVIEW1);//Initialize data in the databaseInitdb (); Btn.setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View v) {//TODO auto-generated method stubString name = Tv1.gettext (). toString (); String age = Tv2.gettext (). toString ();intNAge =0;Try{NAge = integer.valueof (age); }Catch(NumberFormatException exception)                    {Exception.printstacktrace (); NAge =0; } Person person =NewPerson (name,integer.valueof (age)); Array.add (name+" - "+age);                SaveData (person);            Lv.invalidateviews ();    }        }); }Private void Initdb() {db =NewDbservices ( This); arraylist<person> persons = This. Getallobject (); for(intI=0; I<persons.size (); i++) {String object = Persons.get (i). GetName () +" - "+ Persons.get (i). Getage (); This. Array.add (object); } adapter =NewArrayadapter<string> ( ThisAndroid.        R.layout.simple_expandable_list_item_1,array);    Lv.setadapter (adapter); }/** * Save data * @param Student * *       Public void SaveData(Person person) {Bytearrayoutputstream Arrayoutputstream =NewBytearrayoutputstream ();Try{ObjectOutputStream ObjectOutputStream =NewObjectOutputStream (Arrayoutputstream);          Objectoutputstream.writeobject (person); Objectoutputstream.flush ();byteData[] = Arrayoutputstream.tobytearray ();          Objectoutputstream.close ();          Arrayoutputstream.close ();          Sqlitedatabase database = Db.getwritabledatabase (); Database.execsql (' INSERT into Test ' values (?) ',NewObject[] {data});        Database.close (); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); }      } PublicArraylist<person>Getallobject() {arraylist<person> persons =NewArraylist<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));byteData[] = Cursor.getblob (Cursor.getcolumnindex ("Person")); Bytearrayinputstream Arrayinputstream =NewBytearrayinputstream (data);Try{ObjectInputStream InputStream =NewObjectInputStream (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 ()));returnPersons }}
    • Instance Code

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android Basics" Android SQLite store custom objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.