Use SQLite database in Android (ii) Add and remove checks

Source: Internet
Author: User
Tags sqlite database

Defining interfaces

Package Com.example.android_db.service;import Java.util.list;import Java.util.map;public interface PersonService { Public    Boolean Addperson (object[] params);                                      public boolean Deleteperson (object[] params);                                      public boolean Updateperson (object[] params);                                      Public map<string,string> Viewperson (string[] selectionargs);                                      Public list<map<string,string>> listpersonmaps (string[] selectionargs);

Implementing the interface:

Package Com.example.android_db.dao;import Java.util.arraylist;import Java.util.hashmap;import java.util.List; Import Java.util.map;import Android.content.context;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Com.example.android_db.db.dbopenhelper;import com.example.android_    Db.service.personservice;public class Persondao implements Personservice {private Dbopenhelper helper = null; Public Persondao (Context context) {//TODO auto-generated constructor stub helper = new Dbopenhelper (Contex    T); } @Override public Boolean Addperson (object[] params) {//TODO auto-generated method Stub boolean fla        g = false;        Implements the ability to add deletes and modify queries to the database sqlitedatabase = null;            try {String sql = "INSERT into person (name,address,sex) VALUES (?,?,?)";            Database = Helper.getwritabledatabase ();//implementation of write operations on Databases database.execsql (SQL, params);        Flag = true; } catch (ExcePtion e) {//Todo:handle exception e.printstacktrace ();            }finally{if (database!=null) {database.close ();    }} return flag; } @Override public Boolean Deleteperson (object[] params) {//TODO auto-generated Method Stub Boolean        Flag = false;        Sqlitedatabase database = null;            try {String sql = "Delete from the person where id =?";            Database = Helper.getwritabledatabase ();            Database.execsql (sql, params);        Flag = true;                } catch (Exception e) {//Todo:handle Exception}finally{if (database!=null) {            Database.close ();    }} return flag; } @Override public Boolean Updateperson (object[] params) {//TODO auto-generated Method Stub Boolean        Flag = false;        Sqlitedatabase database = null; try {String sql = "Update person set NamE =? , address =?, sex =? WHERE id =?            ";            Database = Helper.getwritabledatabase ();            Database.execsql (sql, params);        Flag = true;                } catch (Exception e) {//Todo:handle Exception}finally{if (database!=null) {            Database.close ();    }} return flag; } @Override public map<string, string> Viewperson (string[] selectionargs) {map<string,string> ma        p = new hashmap<string, string> ();        Sqlitedatabase database = null;            try {String sql = "SELECT * from the person where id =?";            Database = Helper.getreadabledatabase ();            cursor cursor = database.rawquery (sql, Selectionargs);            Gets the number of columns in the database int colums = Cursor.getcolumncount (); while (Cursor.movetonext ()) {for (int i=0;i<colums;i++) {String cols_name = cursor.getc                    Olumnname (i); String ColS_value = cursor.getstring (Cursor.getcolumnindex (cols_name));                    if (cols_value==null) {cols_value = "";                } map.put (Cols_name, Cols_value); }}} catch (Exception e) {//Todo:handle Exception}finally{if (database            !=null) {database.close ();    }} return map; } @Override public list<map<string, string>> listpersonmaps (string[] selectionargs) {//TODO Aut o-generated method Stub list<map<string,string>> List = new Arraylist<map<string,string>> ()        ;        String sql = "SELECT * from person";        Sqlitedatabase database = null;            try {database = Helper.getreadabledatabase ();            cursor cursor = database.rawquery (sql, Selectionargs);            int colums = Cursor.getcolumncount ();              while (Cursor.movetonext ()) {  map<string,string> map = new hashmap<string, string> ();                    for (int i=0;i<colums;i++) {String cols_name = cursor.getcolumnname (i);                    String Cols_value = cursor.getstring (Cursor.getcolumnindex (cols_name));                    if (cols_value==null) {cols_value= "";                } map.put (Cols_name, Cols_value);            } list.add (map);                }} catch (Exception e) {//Todo:handle Exception}finally{if (database!=null) {            Database.close ();    }} return list; }}


To implement Sqliteopenhelper subclasses

Package Com.example.android_db.db;import Android.content.context;import Android.database.DatabaseErrorHandler; Import Android.database.sqlite.sqlitedatabase;import Android.database.sqlite.sqlitedatabase.cursorfactory;import Android.database.sqlite.sqliteopenhelper;public class Dbopenhelper extends Sqliteopenhelper {private static String Nam        E = "mydb.db";//indicates the name of the database private static int version = 2;//indicates the version number of the database public Dbopenhelper (context context) {    Super (context, name, null, version); }//When the database is created, it is executed for the first time, completing the creation of tables on the database @Override public void onCreate (Sqlitedatabase db) {//TODO Auto-genera  Ted method stubs//Supported data types: Integer data, String type, date type, binary data type, String sql = "CREATE table person (ID integer PRIMARY key        Autoincrement,name varchar (+), address varchar (64)) ";    Db.execsql (SQL);  } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//TODO auto-generated Method stub String sql = "Alter TABLe person Add sex varchar (8) ";    Db.execsql (SQL); }}



Test class:

Package Com.example.android_db.test;import Java.util.list;import Java.util.map;import com.example.android_ Db.dao.persondao;import Com.example.android_db.db.dbopenhelper;import com.example.android_ Db.service.personservice;import Android.test.androidtestcase;import Android.util.log;public class MyTest extends androidtestcase {public MyTest () {//TODO auto-generated constructor stubs} public void Createdb (        {Dbopenhelper helper = new Dbopenhelper (GetContext ());    Helper.getwritabledatabase ();        } public void Insertdb () {Personservice service = new Persondao (GetContext ());        Object[] params = {"Reese", "Guangxi", "female"};        Boolean flag = Service.addperson (params);    SYSTEM.OUT.PRINTLN ("--->>" +flag);        } public void Deletedb () {Personservice service = new Persondao (GetContext ());        Object[] params = {1};        Boolean flag = Service.deleteperson (params);    SYSTEM.OUT.PRINTLN ("--->>" +flag);      }     public void UpdateDB () {Personservice service = new Persondao (GetContext ());        Object[] params = {"Harry", "Shanghai", "Ominous", "3"};    Service.updateperson (params);        } public void Viewdb () {Personservice service = new Persondao (GetContext ());        String[] Selectionargs = {"3"};        map<string, string> map = Service.viewperson (Selectionargs);    LOG.I ("Test", "-->>" +map.tostring ());                   } public void Listdb () {Personservice service = new Persondao (GetContext ());        list<map<string,string>> list = Service.listpersonmaps (null);    LOG.I ("Test", "-->>" +list.tostring ()); }}


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.