Android SQLite Alternative Usage (object access)

Source: Internet
Author: User

Using the SQLite database on the Andorid side is often the case, usually for each attribute corresponding to a field, and then the field to read, but today I do not say so. We access them through object serialization. Because a good programmer always has to learn to be lazy.

Demo effect


All right, look at the code.

We'll start by creating a new object, and then we'll access that object.

public class Student implements Serializable {/** *  */private static final long serialversionuid = 1L; String Name;int age;public Student (string name, int age) {super (); 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.) {this.age = age;}}
Then the connection class for the database
/*** * Single-instance mode for database connection * @author Bobo * */public class DBHelper extends Sqliteopenhelper {private static dbhelper DBHelper = n Ull;public static DBHelper Getinstens (context context) {if (DBHelper = = null) {DBHelper = new DBHelper (context);} return dbhelper;} Private DBHelper (Context context) {Super (context, "datebase.db", NULL, 1);//TODO auto-generated constructor stub}@ overridepublic void OnCreate (Sqlitedatabase db) {//TODO auto-generated method Stub// This table takes the binary file to store the object with attention to the second field we are accessing the object here. String sql_class_table= "CREATE table if not exists classtable (_id integer PRIMARY key Autoincrement,classtabledata text) ";d b.execsql (sql_class_table);} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated method stub}}
Finally, a database operation class, the most important method in this class, through the binary stream to convert the object into an object stream and then take out the binary access to the database, and finally the same time. The binary object is first fetched, and then the object is restored through the stream.

/** * Database Operation * @author bobo * */public class Studentservcie {context Context;public Studentservcie (context context) {//TOD O auto-generated Constructor stubthis.context = context;} /** * Save * @param student */public void Saveobject (student student) {Bytearrayoutputstream arrayoutputstream = new Bytearr Ayoutputstream (); try {objectoutputstream objectoutputstream = new ObjectOutputStream (arrayoutputstream); o Bjectoutputstream.writeobject (student); Objectoutputstream.flush (); byte data[] = Arrayoutputstream.tobytearray (); O Bjectoutputstream.close (); Arrayoutputstream.close ();D bhelper dbhelper = dbhelper.getinstens (context); Sqlitedatabase database = Dbhelper.getwritabledatabase ();d atabase.execsql ("INSERT into classtable (classtabledata) VALUES (?) ", new object[] {data});d Atabase.close ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Public Student GetObject () {Student Student = null;dbhelper DBHelper = dbhelper.getinstens (context); Sqlitedatabase Database = DBHelper. Getreadabledatabase ();  cursor cursor = database.rawquery ("SELECT * from classtable", null); if (cursor! = NULL) {while (Cursor.movetonext ()) {byte Data[] = Cursor.getblob (Cursor.getcolumnindex ("Classtabledata")); Bytearrayinputstream Arrayinputstream = new Bytearrayinputstream (data); try {ObjectInputStream inputstream = new ObjectInputStream (arrayinputstream); student = (student) inputstream.readobject (); Inputstream.close (); Arrayinputstream.close (); break;//here to take a data for testing} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} return student;}}
We can also save the list, or the map object, in the same way as above, but the objects inside the map or list must be serialized.

Finally, the test class is given.

public class Mainactivity extends Activity {studentservcie servcie; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); servcie = new Studentservcie (this);} public void onclick (view view) {switch (View.getid ()) {R.id.save:servcie.saveobject (new Student ("Li Lei", 20)); Toast.maketext (This, "Access complete", 0). Show (); Break;case r.id.load:student Student =servcie.getobject (); if (student!=null) Toast.maketext (this, Student.getname () +student.getage (), 0). Show (); break;}}}

Here's a demo: http://download.csdn.net/detail/shengbo1992/7597915

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.