一、SQLite数据库
1.SQLite数据库的特点
安卓手机自带, 小巧, 适合在手机中使用
不区分数据类型(主键除外)
SQL语句和MySQL几乎相同
SQLite不使用JDBC连接, 使用的是Android自有的API
每个数据库对应一个文件
2.创建数据库
定义类继承SQLiteOpenHelper, 实现onCreate(), onUpgrade()
创建该类对象, 调用getWritableDatabse()或者getReadableDatabse()
情况1: 数据库文件不存在, 创建文件, 打开数据库连接(得到SQLiteDatabase对象), 执行onCreate()方法
情况2: 数据库文件存在, 版本号没变, 打开数据库连接
情况3: 数据库文件存在, 版本号提升, 升级数据库, 打开数据库连接,执行onUpgrade()方法
情况4: 数据库文件存在, 版本号降低, 执行onDowngrade()方法, 方法中默认会抛出一个异常
3.创建表或修改表
SQLiteDatabase类的execSQL()方法可以执行一条SQL语句
如果希望创建数据库的时候就创建一些表, 那么这个操作就可以在onCreate()方法中执行
如果希望在数据库升级的时候做类似修改表添加表的操作, 可以在onUpgrade()方法中执行
4.增删改查
execSQL()方法可以进行增删改操作
rawQuery()执行查询操作, 得到Cursor, 调用moveToNext()判断是否包含数据, 调用getString(), getInt()等方法获取数据
insert(), delete(), update(), query() 四个方法内部也是调用execSQL()和rawQuery()的, 它们在ContentProvider中使用更方便
5.事务管理
beginTransaction() 开启事务
setTransactionSuccessful() 设置事务成功标记
endTransaction() 结束事务.
事务结束的时候, 会把最后一个成功标记之前的操作提交, 成功标记之后的操作回滚
6.代码
(1)MyHelper.java
package com.gnnuit.sqlite.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; //自定义类继承SQLiteOpenHelper public class MyHelper extends SQLiteOpenHelper { /** * 由于父类没有无参构造函数, 定义一个构造函数调用父类有参的构造函数 * * @param context * 代表应用程序的环境, 用来确定数据库文件的位置 * @param name * 数据文件的名字 * @param factory * 用来创建Cursor(结果集)的工厂, 默认传null就可以 * @param version * 数据库的版本, 后期用来更新数据库, 从1开始 */ public MyHelper(Context context) { super(context, "myDataBase.db", null, 2); } // 在数据库文件创建之后执行 @Override public void onCreate(SQLiteDatabase db) { System.out.println("onCreate"); // 执行SQL语句,创建表 db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))"); } // 在数据库版本提升之后执行 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("onUpgrade"); db.execSQL("ALTER TABLE account ADD balance INTEGER"); } }
(2)Account.java
package com.gnnuit.sqlite.bean; public class Account { private Integer id; private String name; private Integer balance; public Account() { } public Account(Integer id, String name, Integer balance) { super(); this.id = id; this.name = name; this.balance = balance; } public Account(String name, Integer balance) { super(); this.name = name; this.balance = balance; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getBalance() { return balance; } public void setBalance(Integer balance) { this.balance = balance; } @Override public String toString() { return "Account [id=" + id + ", name=" + name + ", balance=" + balance + "]"; } }
(3)AccountDao.java
package com.gnnuit.sqlite.dao; import java.util.ArrayList; import java.util.List; import com.gnnuit.sqlite.bean.Account; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class AccountDao { private MyHelper helper; public AccountDao(Context context) { helper = new MyHelper(context); } /** * 插入一条记录 * * @param account * 要插入的数据对象 */ public void insert(Account account) { // 获取SQLiteDatabase对象 SQLiteDatabase db = helper.getWritableDatabase(); // 执行一条SQL语句 String sql = "insert into account(name,balance) values(?,?)"; db.execSQL(sql, new Object[] { account.getName(), account.getBalance() }); // 关闭 db.close(); } /** * 根据ID删除记录 * * @param id * 要删除记录的ID */ public void delete(int id) { // 获取SQLiteDatabase对象 SQLiteDatabase db = helper.getWritableDatabase(); // 执行一条SQL语句 String sql = "delete from account where _id=?"; db.execSQL(sql, new Object[] { id }); // 关闭 db.close(); } /** * 更新记录 * * @param account * 要更新的对象 */ public void update(Account account) { // 获取SQLiteDatabase对象 SQLiteDatabase db = helper.getWritableDatabase(); // 执行一条SQL语句 String sql = "update account set name=?,balance=? where _id=?"; db.execSQL(sql, new Object[] { account.getName(), account.getBalance(), account.getId() }); // 关闭 db.close(); } /** * 根据ID查询一条记录 * * @param id * 要查询记录的ID * @return 数据对象 */ public Account query(int id) { Account account = null; // 获取SQLiteDatabase对象 SQLiteDatabase db = helper.getReadableDatabase(); // 执行一条SQL语句 String sql = "select * from account where _id=?"; Cursor cursor = db.rawQuery(sql, new String[] { id + "" }); if (cursor.moveToNext()) {// 判断结果集是否包含下一条数据, 如果包含, 指针自动向后移动 String name = cursor.getString(cursor.getColumnIndex("name"));// 从结果集中获取数据(先根据列名获取索引,再根据索引获取数据) int balance = cursor.getInt(cursor.getColumnIndex("balance")); account = new Account(id, name, balance);// 创建对象, 把数据设置到对象中 } // 关闭 cursor.close(); db.close(); // 返回对象 return account; } /** * 查询所有记录 * * @return 所有记录组成的集合 */ public List<Account> queryAll() { List<Account> accountList = new ArrayList<Account>(); SQLiteDatabase db = helper.getReadableDatabase(); String sql = "select * from account"; Cursor cursor = db.rawQuery(sql, null);// 查询表中所有数据 while (cursor.moveToNext()) { Account account = null; int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int balance = cursor.getInt(cursor.getColumnIndex("balance")); account = new Account(id, name, balance); accountList.add(account); } return accountList; } /** * 分页查询 * * @param pageSize * 每页显示的数量 * @param pageNum * 要查询第几页 * @return */ public List<Account> queryPage(int pageSize, int pageNum) { List<Account> accountList = new ArrayList<Account>(); String index = (pageNum - 1) * pageSize + ""; // 翻页时的起始索引 String count = pageSize + ""; // 查询多少条数据 SQLiteDatabase db = helper.getReadableDatabase(); String sql = "select * from account limit ?,?"; Cursor cursor = db.rawQuery(sql, new String[] { index, count }); while (cursor.moveToNext()) { Account account = null; int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); int balance = cursor.getInt(cursor.getColumnIndex("balance")); account = new Account(id, name, balance); accountList.add(account); } cursor.close(); db.close(); return accountList; } /** * 查询所有记录的游标 * * @return 游标 */ public Cursor queryCursor() { SQLiteDatabase db = helper.getReadableDatabase(); String sql = "select * from account order by balance desc"; return db.rawQuery(sql, null); } /** * 查询所有记录的总数 * * @return 所有记录总数 */ public int queryCount() { int count = -1; SQLiteDatabase db = helper.getReadableDatabase(); String sql = "select count(*) from account"; Cursor cursor = db.rawQuery(sql, null); cursor.moveToNext(); count = cursor.getInt(0); cursor.close(); db.close(); return count; } /** * 事务(转账案例) * * @param fromId * 转账方的ID * @param toId * 接收方的ID * @param amount * 转账金额 */ public void remit(int fromId, int toId, int amount) { SQLiteDatabase db = helper.getWritableDatabase(); try { db.beginTransaction();// 开启事务 db.execSQL("UPDATE account SET balance=balance-? WHERE _id=?", new Object[] { amount, fromId }); db.execSQL("UPDATE account SET balance=balance+? WHERE _id=?", new Object[] { amount, toId }); db.setTransactionSuccessful();// 设置事务成功标记 } finally { db.endTransaction();// 结束事务 db.close(); } } }
二、下拉刷新
1.怎么下载开源工具:github.com上下载PullToRefresh
2.怎么导入:创建Android Project From Existing Code, 选中library, 并且拷贝到工作空间中,在要使用的项目上右键点击Properties, Android选项中导入Library。
3.怎么使用:
1)xml配置<com.handmark.pulltorefresh.library.PullToRefreshListView>
2)Java代码中获取PullToRefreshListView
3)调用setOnRefreshListener()方法添加监听器, 监听刷新操作
4)当刷新时会执行onRefresh()
5)定义一个AsyncTask的子类, 该类实现doInBackground()和onPostExecute()
6)在onRefresh()中创建该类对象, 调用execute()。
4、案例代码:
(1)activity_main.xml
<com.handmark.pulltorefresh.library.PullToRefreshListView android:id="@+id/pull_to_refresh_listview" android:layout_width="fill_parent" android:layout_height="fill_parent" />
(2)MainActivity.java
package com.gnnuit.sqlite.ui; import java.util.List; import com.gnnuit.sqlite.R; import com.gnnuit.sqlite.bean.Account; import com.gnnuit.sqlite.dao.AccountDao; import com.handmark.pulltorefresh.library.PullToRefreshBase; import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode; import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; import com.handmark.pulltorefresh.library.PullToRefreshListView; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.app.Activity; public class MainActivity extends Activity { private PullToRefreshListView prlv; private List<Account> accountList; private AccountDao accountDao; private int pageSize = 1; private BaseAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); prlv = (PullToRefreshListView) this.findViewById(R.id.pull_to_refresh_listview); accountDao = new AccountDao(this); accountList = accountDao.queryPage(10, pageSize); adapter = new MyAdapter(); prlv.setAdapter(adapter); prlv.setMode(Mode.PULL_FROM_END); prlv.setOnRefreshListener(new OnRefreshListener<ListView>() { @Override public void onRefresh(PullToRefreshBase<ListView> refreshView) { new GetDataTask().execute(); } }); } private class MyAdapter extends BaseAdapter { @Override public int getCount() { return accountList.size(); } @Override public Object getItem(int position) { return accountList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView != null ? convertView : View.inflate(MainActivity.this, R.layout.item_listview, null); TextView tv_id = (TextView) v.findViewById(R.id.tv_id); TextView tv_name = (TextView) v.findViewById(R.id.tv_name); TextView tv_balance = (TextView) v.findViewById(R.id.tv_balance); Account account = accountList.get(position); tv_id.setText(account.getId() + ""); tv_name.setText(" " + account.getName()); tv_balance.setText(" " + account.getBalance()); return v; } } private class GetDataTask extends AsyncTask<Void, Void, String[]> { @Override protected String[] doInBackground(Void... params) { try { Thread.sleep(2000); } catch (InterruptedException e) { } return null; } @Override protected void onPostExecute(String[] result) { accountList.addAll(accountDao.queryPage(10, ++pageSize)); adapter.notifyDataSetChanged(); prlv.onRefreshComplete(); super.onPostExecute(result); } } }