Android object link ing framework ormlite Learning

Source: Internet
Author: User

I always felt that it was a little troublesome to use the original SQLLiteHelper to operate the database. I found some android database orm frameworks on the Internet and compared them. Now there seem to be a lot of people using ormlite. I found ormlite official documents on the Internet, according to the official documentation, today I wrote a demo, mainly for user registration, user information viewing and deletion, and I used the same orm framework Afinal before to run the demo, however, Afinal is not as powerful as ormlite.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + authorization + 88rWlo6zE3Lm7v7S1w7autcSjrLbgv7S/authorization + authorization/g06a1xMG9uPZqYXKw/KOoxL/authorization Export/yaGjPC9wPgo8cD48L3A + cjxwp450vcd4kpha + export = "brush: java;"> @ DatabaseTable (tableName = "tb_user") // if no particular tableName = "tb_user" is specified ", by default, the class name can be used as the table name // annotation @ Entity can also be used here, because ORMLite supports both its own annotations (@ DatabaseTable and @ DatabaseField) and many from javax. standard annotation in the persistence package. // You can use more standard JPA annotations from the javax. persistence package. Public class User {// User id/*** id: whether the field is a primary key. The default value is false * generatedId: whether the field is automatically added. The default value is false. * Note: Only one id and generatedId can be specified. Otherwise, an error will be reported * // you can use javax. persistence annotation: @ Id, @ Column @ DatabaseField (generatedId = true) private int userId; // userName @ DatabaseFieldprivate String userName; // password @ DatabaseFieldprivate String password; public User () {// The No-argument constructor must be provided so that the queried object can be returned during the query} public User (int userId, String userName, String password) {this. userId = userId; this. userName = userName; this. password = password;} public int getUserId () {return userId;} public void setUserId (int userId) {this. userId = userId;} public String getUserName () {return userName;} public void setUserName (String userName) {this. userName = userName;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password ;}}

3. Create SQLLiteOpenHelper. Here there are two important classes: OrmLiteSqliteOpenHelper (when your application is loaded, create and update databases, and provide DAO classes for other classes, onCreate (SQLiteDatabasesqliteDatabase, connectionSource

ConnectionSource) and onUpgrade (SQLiteDatabasedatabase, ConnectionSource

ConnectionSource, intoldVersion, int newVersion ). runtimeExceptionDao (by default, most dao Methods throw SQLException, because SQLException is the default exception thrown by most jdbc and other SQL calls. However, on the android platform, especially the vast majority of exceptions inherit RuntimeException, and a RuntimeExceptionDao is added to encapsulate all runtime exceptions thrown by calling the underlying dao method at runtime .)

Public class DatabaseHelper extends OrmLiteSqliteOpenHelper {// database name private static final String DATABASE_NAME = "helloAndroid. db "; // database version private static final int DATABASE_VERSION = 1;/*** contains two generic types: * The first generic table DAO operation class * the second one indicates the primary key type of the operation class */private Dao
 
  
UserDao = null; private RuntimeExceptionDao
  
   
SimpleRuntimeDao = null; public DatabaseHelper (Context context) {super (context, DATABASE_NAME, null, DATABASE_VERSION) ;}@ Overridepublic void onCreate (SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {try {Log. I (DatabaseHelper. class. getName (), "onCreate"); TableUtils. createTable (connectionSource, User. class);} catch (SQLException e) {Log. e (DatabaseHelper. class. getName (), "Can't create database", e); throw new RuntimeException (e);}/*** insert a data entry */public void insert (User user) {RuntimeExceptionDao
   
    
Dao = getSimpleDataDao (); // create a data record in the database by creating an object. If 1 is returned successfully, a data Log is inserted. I ("test", "dao =" + dao + "user =" + user); int returnValue = dao. create (user); Log. I ("test", "returned value after data insertion:" + returnValue);}/*** query all user information * @ return */public List
    
     
FindAllUser () {RuntimeExceptionDao
     
      
Dao = getSimpleDataDao (); return dao. queryForAll ();}/*** Delete the first user information */public void deleteById () {RuntimeExceptionDao
      
        Dao = getSimpleDataDao (); List
       
         List = dao. queryForAll (); // if (list. size ()> 0) {int returnValue = dao. deleteById (list. get (0 ). getUserId (); Log. I ("test", "Return Value After deleting a piece of data:" + returnValue) ;}/ *** batch delete user information */public void deleteByIds () {RuntimeExceptionDao
        
          Dao = getSimpleDataDao (); List
         
           List = dao. queryForAll (); List
          
            Ids = new ArrayList
           
             (); If (list. size ()> 0) {for (User u: list) {ids. add (u. getUserId ();} // returns the number of deleted records int returnValue = dao. deleteIds (ids); Log. I ("test", "Return Value after batch deletion:" + returnValue) ;}} public RuntimeExceptionDao
            
              GetSimpleDataDao () {if (simpleRuntimeDao = null) {simpleRuntimeDao = getRuntimeExceptionDao (User. class);} Log. I ("test", "simpleRuntimeDao ====" + simpleRuntimeDao); return simpleRuntimeDao ;} /*** this method is called when your application is upgraded and has a higher version number. So you need to adjust the data to adapt to the new version */@ Overridepublic void onUpgrade (SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {Log. I ("test", "update .... "); try {Log. I (DatabaseHelper. class. getName (), "onUpgrade"); // Delete the old version of TableUtils. dropTable (connectionSource, User. class, true); // create a new version onCreate (sqliteDatabase, connectionSource);} catch (SQLException e) {Log. e (DatabaseHelper. class. getName (), "Can't drop databases", e); throw new RuntimeException (e) ;}} public Dao
             
               GetDao () throws SQLException {if (userDao = null) {userDao = getDao (User. class) ;}return userDao ;}}
             
            
           
          
         
        
       
      
     
    
   
  
 

4: The next step is Activity.

MainActivity: when the program runs, it enters the class. It mainly displays the buttons on the page and the queried user information.

Public class MainActivity extends Activity {Button button1; // register Button button2; // display Button button3; // delete Button button4; // Delete multiple buttons TextView textView; // display the queried user information DatabaseHelper helper = new DatabaseHelper (this); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); button1 = (Button) this. findViewById (R. id. main_btn_regist); button2 = (Button) this. findViewById (R. id. main_btn_show); button3 = (Button) this. findViewById (R. id. main_btn_delete); button4 = (Button) this. findViewById (R. id. main_btn_deleteAll); textView = (TextView) this. findViewById (R. id. main_show_user); // click the register button to go to the registration page. The registration page is button1.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {Intent intent = new Intent (); intent. setClass (MainActivity. this, RegistActivity. class); startActivity (intent) ;}}); // click "show" to go to the user information display page and display the registered user information button2.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {List
 
  
UserList = helper. findAllUser (); String str = ""; if (userList. size ()> 0) {// display the queried User information for (user: userList) {str + = "User" + user. getUserId () + ":" + user. getUserName () + "Password:" + user. getPassword ();} textView. setText (str);} else {textView. setText ("dear! Not registered yet! ") ;}}); // Delete a record, button3.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {helper. deleteById () ;}}); // batch Delete button4.setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View v) {helper. deleteByIds () ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}
 

Corresponding layout file: main. xml

     
          
          
          
          
  
 

RegistActivity: User Registration class

/*** User registration ** @ author leox **/public class RegistActivity extends Activity {EditText userNameEdit; // username edit box EditText passwordEdit; // password edit box Button reButton; // Registration button DatabaseHelper helper = new DatabaseHelper (this); @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); userNameEdit = (EditText) this. findViewById (R. id. et_username); passwordEdit = (EditText) this. findViewById (R. id. et_password); reButton = (Button) this. findViewById (R. id. btn_regist); reButton. setOnClickListener (new myClickListener ();} @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. main, menu); return true;} class myClickListener implements OnClickListener {@ Overridepublic void onClick (View v) {// userName String userName = userNameEdit. getText (). toString (); // password String password = passwordEdit. getText (). toString (); User user = new User (); user. setUserName (userName); user. setPassword (password); // Insert the registered user information helper. insert (user); Intent intent = new Intent (); intent. setClass (RegistActivity. this, MainActivity. class); startActivity (intent );}}}

Corresponding layout file: activity_main.xml

     
          
          
           
       
          
          
           
       
          
  
 








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.