• Android SQLite的使用,基本的增删改查效果,以及ListView的效果显示


     
    1
    package com.example.sqlitetest; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 import android.content.ContentValues; 6 import android.content.Context; 7 import android.database.Cursor; 8 import android.database.sqlite.SQLiteDatabase; 9 /**
      *Dao层的编写,提供增删改查,查询全部等功能
       */

    10
    public class PersonDao { 11 private MyHelper helper; 12 13 public PersonDao(Context context) { 14 helper = new MyHelper(context); 15 } 16 17 /** 18 * 新增数据 19 * 20 * @param p 21 */ 22 public void insert(Person p) { 23 SQLiteDatabase db = helper.getWritableDatabase(); 24 db.execSQL("INSERT INTO person(name, balance) VALUES(?,?)", 25 new Object[] { p.getName(), p.getBalance() }); 26 db.close(); 27 } 28 29 /** 30 * 根据Id删除数据 31 * 32 * @param id 33 */ 34 public void delete(int id) { 35 SQLiteDatabase db = helper.getWritableDatabase(); 36 db.execSQL("DELETE FROM person WHERE id=?", new Object[] { id }); 37 db.close(); 38 } 39 40 /** 41 * 更新数据 42 * 43 * @param p 44 * @return 45 */ 46 public void update(Person p) { 47 SQLiteDatabase db = helper.getWritableDatabase(); 48 ContentValues values = new ContentValues(); 49 values.put("name", p.getName()); 50 values.put("balance", p.getBalance()); 51 db.update("person", values, "id=?", new String[] { p.getId() + "" }); 52 db.close(); 53 } 54 55 /** 56 * 根据Id查询出一条数据 57 * 58 * @param id 59 * @return 60 */ 61 public Person query(int id) { 62 SQLiteDatabase db = helper.getReadableDatabase(); 63 Cursor c = db.query("person", new String[] { "name", "balance" }, 64 "id=?", new String[] { id + "" }, null, null, null); 65 Person p = null; 66 if (c.moveToNext()) { 67 p = new Person(); 68 p.setId(id); 69 p.setName(c.getString(c.getColumnIndex("name"))); // 获取name列的索引, 70 // 获取指定索引上的字符串数据, 71 // 设置为name属性 72 p.setBalance(c.getInt(1)); // 直接获取1号索引列上的数据, 设置为balance属性 73 } 74 c.close(); 75 db.close(); 76 return p; 77 } 78 79 /** 80 * 查询所有数据,返回一个List集合 81 * 82 * @return 83 */ 84 public List<Person> queryAll() { 85 SQLiteDatabase db = helper.getReadableDatabase(); 86 Cursor c = db.query("person", null, null, null, null, null, null); 87 List<Person> persons = new ArrayList<Person>(); 88 while (c.moveToNext()) { 89 Person p = new Person(); 90 p.setId(c.getInt(0)); 91 p.setName(c.getString(1)); 92 p.setBalance(c.getInt(2)); 93 persons.add(p); 94 } 95 c.close(); 96 db.close(); 97 return persons; 98 } 99 100 }
     1/**
      *创建一个类实现SQLiteOpenHelper类,该对象用于建立于数据库的连接
    2 */ 3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5 import android.database.sqlite.SQLiteOpenHelper; 6 7 public class MyHelper extends SQLiteOpenHelper { 8 9 /** 10 * 创建工具对象, 该对象可以用来打开一个数据库连接 11 * @param context 当前应用的上下文环境对象 12 * @param name 数据库文件的名字 13 * @param factory 游标工厂, 填null就是默认工厂 14 * @param version 数据库版本号(从1开始)   
    15 * 当项目运行时候会检测version版本号有没有改变,若是改变了,则会走onUpgrade方法更新数据库,诺是 版本没有改变,诺数据库不存在则创建数据库,诺存在两个方法都不执行
       */ 16 public MyHelper(Context context) { 17 super(context, "lucy.db", null, 1); 18 } 19 20 @Override 21 public void onCreate(SQLiteDatabase db) { // 数据库创建时执行 22 System.out.println("onCreate"); 23 db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))"); // 创建表的代码 24 } 25 26 @Override 27 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 数据库升级时执行 28 System.out.println("onUpgrade"); 29 db.execSQL("ALTER TABLE person ADD balance INTEGER"); // 修改表的代码 30 } 31 32 }
     1 /**
      
    2 *创建测试类,用来测试dao层的增删改查方法,Android的测试类需要继承AndroidTestCase类,该类即为一个测试类,需要注意的是在AndroidMainfest.xml文件中需要引入一下配置,
      
    *后面会列出ui界面的xml文件
       <uses-library android:name="android.test.runner" />   
        <instrumentation
            android:name="android.test.InstrumentationTestRunner"
            android:targetPackage="com.example.sqlitetest" />

      
    */
    3 import java.util.List; 4 import java.util.Random; 5 6 import android.test.AndroidTestCase; 7 8 public class SQLiteTest extends AndroidTestCase { 9 10 // 测试方法执行时: 把apk上传到手机 -> 安装 -> 创建SQLiteTest对象 -> 调用setContext()方法设置进来一个Context对象 11 12 public void testCreateDatabase() { 13 MyHelper helper = new MyHelper(getContext()); // 类似Activity类中的getApplicationContext() 14 helper.getWritableDatabase(); // 获取一个可写的数据库 15 /* 16 * 1.数据库不存在: 创建数据库, 执行onCreate() 17 * 2.数据库存在, 版本没变: 找到之前的数据库文件, 打开 18 * 3.数据库存在, 版本改变: 找到之前数据库文件, 打开, onUpgrade() 19 */ 20 } 21 /** 22 * 一次性插入100條數據 23 */ 24 public void testInsert() { 25 PersonDao dao = new PersonDao(getContext()); 26 for (int i = 0; i < 100; i++) 27 dao.insert(new Person("Test" + i, new Random().nextInt(10000))); 28 } 29 /** 30 * 删除id是1的数据 31 */ 32 public void testDelete() { 33 PersonDao dao = new PersonDao(getContext()); 34 dao.delete(1); 35 } 36 /** 37 * 更新id是2的数据 38 */ 39 public void testUpdate() { 40 PersonDao dao = new PersonDao(getContext()); 41 dao.update(new Person(2, "小洺", 1000000)); 42 } 43 /** 44 * 查询id是1,2,3的数据 45 */ 46 public void testQuery() { 47 PersonDao dao = new PersonDao(getContext()); 48 System.out.println(dao.query(1)); 49 System.out.println(dao.query(2)); 50 System.out.println(dao.query(3)); 51 } 52 /** 53 * 查询所有的数据 54 */ 55 public void testQueryAll() { 56 PersonDao dao = new PersonDao(getContext()); 57 List<Person> persons = dao.queryAll(); 58 for (Person person : persons) { 59 System.out.println(person); 60 } 61 } 62 }
     1 package com.example.sqlitetest;
     2 //实体类Person的编写,对该类进行Crud的操作
      3 public class Person {
     4     @Override
     5     public String toString() {
     6         return "Person [id=" + id + ", name=" + name + ", balance=" + balance
     7                 + "]";
     8     }
     9 
    10     private Integer id;
    11 
    12     public Person(String name, Integer balance) {
    13         super();
    14         this.name = name;
    15         this.balance = balance;
    16     }
    17 
    18     public Person() {
    19         // TODO Auto-generated constructor stub
    20     }
    21 
    22     private String name;
    23     private Integer balance;
    24 
    25     public Integer getId() {
    26         return id;
    27     }
    28 
    29     public void setId(Integer id) {
    30         this.id = id;
    31     }
    32 
    33     public String getName() {
    34         return name;
    35     }
    36 
    37     public void setName(String name) {
    38         this.name = name;
    39     }
    40 
    41     public Integer getBalance() {
    42         return balance;
    43     }
    44 
    45     public void setBalance(Integer balance) {
    46         this.balance = balance;
    47     }
    48 }

    以上即可完成一个简单的sqlite数据库的增删改查的功能测试。

    下面是将Sqlite中的数据以ListView模式进行

     1 package com.example.sqlitetest;
     2 
     3 import java.util.List;
     4 import android.app.Activity;
     5 import android.os.Bundle;
     6 import android.view.View;
     7 import android.view.ViewGroup;
     8 import android.widget.BaseAdapter;
     9 import android.widget.ListView;
    10 import android.widget.TextView;
    11 
    12 public class MainActivity extends Activity {
    13     private List<Person> persons;
    14     private PersonDao dao;
    15 
    16     public void onCreate(Bundle savedInstanceState) {
    17         super.onCreate(savedInstanceState);
    18           dao = new PersonDao(getApplicationContext());
    19             persons = dao.queryAll();
    20             System.err.println("<><><><><><><>><>="+persons.size());
    21             ListView personLV = (ListView) findViewById(R.id.personLV);
    22             personLV.setAdapter(new MyBaseAdapter()); //给ListView设置适配器,适配器会自动生成条目添加到ListView中去
    23 //
    24 } 25 //编写自定义的Adapter继承BaseAdapter,拿到一个适配器
    26 private class MyBaseAdapter extends BaseAdapter { 27 public int getCount() { // 获取条目总数
    28 return persons.size(); 29 } 30 31 public Object getItem(int position) { // 获取指定位置上的数据
    32 return persons.get(position); 33 } 34 35 public long getItemId(int position) { // 获取条目的Id
    36 return position; 37 } 38 39 public View getView(int position, View convertView, ViewGroup parent) { // 获取指定位置上的View根据Person的对象创建一个View, 40 // 鏍规嵁Person瀵硅薄鍒涘缓涓�釜View杩斿洖 41 View view = convertView == null ? View.inflate( 42 getApplicationContext(), R.layout.item, null) : convertView; // 根据布局文件生成一个View 43 TextView idTV = (TextView) view.findViewById(R.id.idTV); // 使用view获取TextView,不要再activity中找,匿名内部类了
    44
    45 TextView nameTV = (TextView) view.findViewById(R.id.nameTV); 46 TextView balanceTV = (TextView) view.findViewById(R.id.balanceTV); 47 48 Person p = persons.get(position); // 获取指定位置撒谎那个的Person 对象
    49 idTV.setText(p.getId() + ""); // 给TextView 替换文本,不用要些int 类型的否则会去查找R文件的数据
    50 // 鍚﹀垯浼氭煡R鏂囦欢 51 nameTV.setText(p.getName()); 52 balanceTV.setText(p.getBalance() + ""); 53 54 return view; 55 } 56 } 57 }

    给出Item 的ui模版 ,一个线性布局里面放置三个TextView分别存放id  name  blanace

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="match_parent"
     4     android:layout_height="match_parent"
     5     android:orientation="horizontal"
     6     android:padding="10dp" >
     7 
     8     <TextView
     9         android:id="@+id/idTV"
    10         android:layout_width="0dp"
    11         android:layout_height="wrap_content"
    12         android:layout_weight="1"
    13         android:text="15"
    14         android:textSize="30sp" />
    15 
    16     <TextView
    17         android:id="@+id/nameTV"
    18         android:layout_width="0dp"
    19         android:layout_height="wrap_content"
    20         android:layout_weight="2"
    21         android:singleLine="true"
    22         android:text="姓名"
    23         android:textSize="30sp" />
    24 
    25     <TextView
    26         android:id="@+id/balanceTV"
    27         android:layout_width="0dp"
    28         android:layout_height="wrap_content"
    29         android:layout_weight="2"
    30         android:text="1234"
    31         android:textSize="30sp" />
    32 
    33 </LinearLayout>
    View Code


    给出main.xml

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     android:layout_width="fill_parent"
     4     android:layout_height="fill_parent"
     5     android:orientation="vertical" >
     6 
     7     <LinearLayout 
     8         android:background="#555555"
     9         android:layout_width="match_parent"
    10         android:layout_height="wrap_content"
    11         android:orientation="horizontal"
    12         android:padding="10dp" >
    13 
    14         <TextView
    15             android:id="@+id/idTV"
    16             android:layout_width="0dp"
    17             android:layout_height="wrap_content"
    18             android:layout_weight="1"
    19             android:text="ID"
    20             android:textSize="30sp" />
    21     
    22         <TextView
    23             android:id="@+id/nameTV"
    24             android:layout_width="0dp"
    25             android:layout_height="wrap_content"
    26             android:layout_weight="2"
    27             android:text="Name"
    28             android:textSize="30sp" />
    29     
    30         <TextView
    31             android:id="@+id/balanceTV"
    32             android:layout_width="0dp"
    33             android:layout_height="wrap_content"
    34             android:layout_weight="2"
    35             android:text="Balance"
    36             android:textSize="30sp" />
    37     
    38     </LinearLayout>
    39     
    40     <ListView
    41         android:id="@+id/personLV"
    42         android:layout_width="fill_parent"
    43         android:layout_height="fill_parent" >
    44     </ListView>
    45 
    46 </LinearLayout>
    View Code

    完成一个ListView布局的demo

     编写测试用例的时候需要注意的

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.sqlitetest"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="15" />
        <instrumentation
            android:name="android.test.InstrumentationTestRunner"
            android:targetPackage="com.example.sqlitetest" /> <!-- 
                        编写AndroidTestCase 测试类时需要有该节点配置
                 -->
    
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
              <uses-library android:name="android.test.runner" /> <!-- 
                        编写AndroidTestCase 测试类时需要有该节点配置
                 -->
    
            <activity
                android:name=".MainActivity"
                android:label="@string/title_activity_main" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>
  • 相关阅读:
    绑定姿势
    Mesh.CombineMeshes
    Mono vs IL2CPP
    lua keynote2
    lua keynote
    游戏编程模式KeyNote
    架构、性能和游戏
    Canvas
    AssetBundle Manager
    Loading AssetBundle Manifests
  • 原文地址:https://www.cnblogs.com/sm-myworks/p/3703388.html
Copyright © 2020-2023  润新知