[Android Basics] Android SQLite stores custom objects, androidsqlite
Android SQLite stores custom objects
Data types that can be stored in the SQLite database include NULL, INTEGER, REAL (float type), TEXT, and BOOL. There are five data types in total. In Android development, the general method for storing data is that the database attribute is a member variable of the class, such:
To store a person's name and age, define them as two member variables in the class.
class Person{ private String name; private int age;}
In the database, they are stored as two fields.
-Name TEXT
-Age INTEGER
Now I want to introduce this method to directly store the Persond1 instance in the database, that is, to store objects in the database.
The specific method is to serialize the object into a byte stream string and store the byte stream string in the database as TEXT, deserialize byte streams into objects. Therefore, our object class must implement the Serializable interface class.
The following is an instance (download ):
- The first is the Person class, which is the entity class we store. Only the set and get methods are available, and the serialization interface is implemented.
Package com. databasetest; import java. io. serializable; @ SuppressWarnings ("serial") public class Person implements Serializable {private String name; private int age; public Person () {this ("", 0 ); // default value} 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 ;}}
- Then there is the auxiliary class of the database.
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 (); // CREATE the mail TABLE String create_mail_ SQL = "CREATE TABLE if not exists [Test]" + "(_ id integer primary key autoincrement, person text )"; db.exe cSQL (create_mail_ SQL); db. setTransactionSuccessful (); db. endTransaction () ;}@ Override public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stub }}
- Next, the instance interface is displayed. There are two input boxes for entering the name and age, one button for confirmation, and one list for displaying 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 =" 10 "android: hint = "name"/> <EditText android: id = "@ + id/editText2" android: layout_width = "fill_parent" android: layout_height = "wrap_content" android: EMS = "10" android: hint = "Age"> <requestFocus/> </EditText> <Button android: id = "@ + id/button1" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: text = "OK to add"/> <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>
The saveData method is used to store objects. getAllObject is used to obtain all the Person objects in the database.
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); // obtain the control tv1 = (EditText) findViewById (R. id. editText1); tv2 = (EditText) findViewById (R. id. editText2); btn = (Button) findViewById (R. id. button1); lv = (ListView) findViewById (R. id. listView1); // initialize the data in the database 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 = I Nteger. 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 ). ge TName () + "-" + 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);}/*** save data * @ 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.exe cSQL ("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) inputStream. readObject (); persons. add (person); inputStream. close (); arrayInputStream. close ();} catch (Exception e) {e. printStackTrace () ;}} Log. d ("Persons-Count", Integer. toString (persons. size (); return persons ;}}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.