Analysis of common operation examples in Android database _android

Source: Internet
Author: User
Tags sqlite static class

The examples in this article describe the common operations of databases in Android. Share to everyone for your reference, specific as follows:

Android database operation is very common, we will often use, the operation of the method also has a variety of forms, here I have the most common form of the two forms of record, for later use for easy to view. I don't write annotations and explanations, because the Android database operation is essentially the same as other database operations. Some of the basic explanations needed are in the code, directly on the code.

Simple Directory of code files:

First, this class is a database helper class, Dbhelper.java, and the code is as follows:

Package net.loonggg.db; 
Import Android.content.Context; 
Import Android.database.sqlite.SQLiteDatabase; 
Import Android.database.sqlite.SQLiteOpenHelper; 
/** 
 * Database Help class, inherit Android Sqliteopenhelper primarily for database creation and update 
 * * 
 @author loonggg 
 * 
* * Class DBHelper extends Sqliteopenhelper {public 
 dbhelper (context) { 
  Super (context, DBInfo.DB.DB_ NAME, NULL, DBInfo.DB.DB_VERSION); 
 @Override public 
 void OnCreate (Sqlitedatabase db) { 
  db.execsql (DBInfo.Table.USER_INFO_CREATE); 
 } 
 @Override public 
 void Onupgrade (sqlitedatabase db, int oldversion, int newversion) { 
  Db.execsql ( DBInfo.Table.USER_INFO_DROP); 
  OnCreate (db); 
 } 


Next is the database information class, Dbinfo.java, the code is as follows:

Package net.loonggg.db; 
/** 
 * Database Information class, mainly to save some database version, name, and database table creation statements and table information, through this class record, convenient operation 
 * * 
 @author loonggg 
 * 
* * * * public class DBInfo { 
 /** 
  * Database Info 
  * 
  * @author LOONGGG * */public 
 static class DB {
   //database name public 
  static final String db_name = "test.db"; 
  The version number of the database public 
  static final int db_version = 1; 
 } 
 /** * 
  database table Information 
  * * 
  @author LOONGGG * */public 
 Static class Table {public 
  static Final String user_info_tb_name = "user_table"; 
  public static final String user_info_create = "CREATE TABLE IF not EXISTS" 
    + user_info_tb_name 
    + "(_id intege R PRIMARY key,userid text,username text) "; 
  public static final String User_info_drop = "DROP TABLE" 
    + user_info_tb_name; 
 } 
}

Again is the database operation class, Dbservice.java, the code is as follows:

Package net.loonggg.service; 
Import java.util.ArrayList; 
Import Java.util.HashMap; 
Import java.util.List; 
Import Net.loonggg.db.DBHelper; 
Import net.loonggg.db.DBInfo.Table; 
Import android.content.ContentValues; 
Import Android.content.Context; 
Import Android.database.Cursor; 
Import Android.database.sqlite.SQLiteDatabase; /** * Database Operation class, the main function of this class is: some of the methods to store database operations here are some examples: including database additions and deletions, there are two methods of operation, each has advantages and disadvantages, are in the interpretation of * * @author LOONGGG * * * * * * * 
 Lass Dbservice {private DBHelper dbhelper = null; 
 Public Dbservice {dbhelper = new DBHelper (context); /** * Add a record to the database * * @param ID * @param name */public void Add (string id, string name) {Sqliteda 
  Tabase db = Dbhelper.getwritabledatabase (); Bad: No return value, unable to determine whether to insert success Db.execsql (INSERT INTO user_table (userid,username) VALUES (?,?), new object[] {ID, nam 
  e}); 
 Db.close (); Public long addandroid (string ID, string name) {Sqlitedatabase db = Dbhelper.getwritabledataBase (); 
  Contentvalues values = new Contentvalues (); 
  Values.put ("userId", id); 
  Values.put ("UserName", name); 
  Benefits: There is a return value of long result = Db.insert (table.user_info_tb_name, null, values);//return value is inserted in the first few rows, greater than 0 represents the addition of success db.close (); 
 return result;  /** * Query If a record exists * * @param name * @return/public boolean find (String name) {Sqlitedatabase db 
  = Dbhelper.getreadabledatabase (); 
  Cursor Cursor = Db.rawquery ("select * from user_table where userName =?", new string[] {name}); 
  Boolean result = Cursor.movetonext (); 
  Db.close (); 
 return result; 
  public boolean findandroid (String name) {Sqlitedatabase db = Dbhelper.getreadabledatabase (); 
  Cursor Cursor = db.query (Table.user_info_tb_name, null, "UserName =?", new string[] {NAME}, NULL, NULL, NULL); 
  Boolean result = Cursor.movetonext ()//True represents the lookup of Db.close (); 
 return result; /** * Modify a record * * @param ID * @param name */public void update (S)Tring ID, String name {sqlitedatabase db = Dbhelper.getwritabledatabase (); Disadvantage no return value db.execsql ("Update user_table set userName =? 
  where userId =? ", new object[] {name, id}); 
 Db.close (); 
  public int updateandroid (string ID, string name) {Sqlitedatabase db = Dbhelper.getwritabledatabase (); 
  Contentvalues values = new Contentvalues (); 
  Values.put ("UserName", name); 
  The return value greater than 0 represents a modified update success int result = Db.update (Table.user_info_tb_name, values, "UserId =?", new string[] {ID}); 
  Db.close (); 
 return result; /** * Delete a record * * @param name */public void Delete (String name) {Sqlitedatabase db = Dbhelper.getwri 
  Tabledatabase (); 
  Db.execsql ("Delete from user_table where userName =?", new string[] {name}); 
 Db.close (); 
  public int deleteandroid (String name) {Sqlitedatabase db = Dbhelper.getwritabledatabase (); int result = Db.delete (Table.user_info_tb_name, "userName =?", new string[] {NAME});The return value is the number of rows affected, and greater than 0 represents the successful db.close (); 
 return result; /** * Returns all database information * * @return/public list 

The

is finally mainactivity, simply called, these operations, the code is as follows:

Package net.loonggg.test; 
Import Net.loonggg.service.DBService; 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.widget.Button; 
 public class Mainactivity extends activity {private Button queryone; 
 Private Button Insert; 
 Private Button Update; 
 Private Button Delete; 
 Private Button FindAll; 
 Private Dbservice service; 
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.activity_main); 
  Queryone = (Button) Findviewbyid (R.id.queryone); 
  Insert = (Button) Findviewbyid (R.id.insert); 
  Update = (Button) Findviewbyid (r.id.update); 
  Delete = (Button) Findviewbyid (r.id.delete); 
  FindAll = (Button) Findviewbyid (R.id.findall); 
  Queryone.setonclicklistener (New Buttonlistener ()); 
  Insert.setonclicklistener (New Buttonlistener ()); 
  Update.setonclicklistener (New Buttonlistener ()); 
  Delete.setonclicklistener (New Buttonlistener ()); FindAll.Setonclicklistener (New Buttonlistener ()); 
 Service = new Dbservice (this); Class Buttonlistener implements View.onclicklistener {@Override public void OnClick (View v) {switch (v.get 
    Id ()) {case R.id.queryone://Service.find ("LOONGGG"); 
    Service.findandroid ("LOONGGG"); 
   Break 
    Case R.id.insert://Service.add ("1", "LOONGGG"); 
    Service.addandroid ("2", "Heihei"); 
   Break 
    Case R.id.update://Service.update ("1", "Timmy"); 
    Service.updateandroid ("1", "haha"); 
   Break 
    Case R.id.delete://Service.delete ("Timmy"); 
    Service.deleteandroid ("Heihei"); 
   Break 
    Case R.id.findall://Service.findall (); 
    Service.findallandroid (); 
   Break 
   Default:break;

 } 
  } 
 } 
}

The

also has mainactivity corresponding layout file, Activity_main.xml:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o" rientation= "vertical" > <button android:id= "@+id/queryone" android:layout_width= "Fill_parent" Android:lay out_height= "wrap_content" android:text= "Query a record"/> <button android:id= "@+id/insert" android:layout_width= 
  "Fill_parent" android:layout_height= "Wrap_content" android:text= "Add"/> <button android:id= "@+id/update" Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Modify"/> <Button a  Ndroid:id= "@+id/delete" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "Delete" /> <button android:id= "@+id/findall android:layout_width=" fill_parent "android:layout_height=" Wrap_cont ENT "android:text=" Query all "/> &LT;/LINEARLAYOUT&GT 

Here is the introduction, the code is not advanced, the reason for the record, is to save the time to use when convenient to view, of course, this code for beginners, but also very helpful.

I hope this article will help you with the Android program.

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.