編輯:關於 Android 程式設計
SQLite 是一款數據庫,與 Oracle、SQLServer、MySQL 同屬關系型數據庫。Android 系統自帶了這個輕量級的 SQLite。
輕量級:只有一個動態庫,以單個文件的形式進行存取;
零配置:無需安裝即可使用;
跨平台:支持多個操作系統;
嵌入式:可嵌入到手機設備中。
在程序內部,任何位置都能通過數據庫名稱訪問數據庫,而其他程序則無法通過名稱對其訪問。
路徑:data/data/應用程序包名/database/****
NULL:空值;
INTEGER:整型;
VARCHAR:可變長度的字符數據;
TEXT:文本字符串;
BOOLEAN:布爾值。
1、創建表
create table if not exists 表名(字段名稱 字段類型 primary key autoincrement,字段名稱 字段類型,.....)
create table if not exists user(_id integer primary key autoincrement,name varchar(20),age integer)
2、插入數據
insert into 表名(字段S) values(值S)
insert into user(name,age) values('小明',20)
3、修改數據
update 表名 set 字段名稱=值 where 字段 = 值
update user set name='小攀' where _id=1
4、查詢數據
select (字段S) from 表名 where 字段 = 值
select * from user
模糊查詢:select * from 表名 where name like '%o%'
5、刪除數據
delete from 表名 where 字段 = 值
delete from user where _id=2
1、SQLiteDatabase:管理和操作數據庫。
特點:提供了一個管理數據庫的類,提供了增刪改查的方法;數據庫名稱唯一,創建一次之後再操作即為打開數據。獲取數據庫對象的方法為 Context.openOrCreateDatabase(String name, int mode, CursorFactory factory)。SQLiteDatabase 主要提供的方法包括:void execSQL(String sql) 執行 sql 語句;Cursor rawQuery(String sql, String[] selectionArgs) 查詢符合條件的內容。此外還有封裝好的方法,適用於不熟悉 SQL 的用戶:insert() 插入數據、update() 修改數據、query() 查詢內容、delete() 刪除數據。
2、SQLiteOpenHelper:用於數據庫的創建和版本更新。
3、Cursor(游標):默認位置顯示在數據之上。
boolean cursor.move(int offset):游標向上或向下移動指定行數,offset 為正表示向上、為負表示向下,並判斷當前數據是否存在;
boolean cursor.moveToNext():移動到下一條並判斷是否存在;
boolean cursor.moveToPrevious():移動到上一條並判斷是否存在;
boolean cursor.moveToFirst():移動到第一條並判斷是否存在。
下面通過一個完整的通訊錄案例來演示 SQLite 的增刪改查。首先是 MainActivity:
package com.qf.day13_phonebook; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.qf.day13_phonebook.db.DbService; public class MainActivity extends Activity { //控件 private ListView lv; //數據源 private Cursor cursor; //適配器 private SimpleCursorAdapter adapter; private DbService dbService; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); dbService = new DbService(this); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); setListAdapter(); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, final int position, long id) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setIcon(R.drawable.ic_launcher); builder.setTitle("請選擇你的操作"); builder.setItems(new String[]{"編輯聯系人","刪除聯系人"}, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // 點擊的是那個 Item switch (which) { case 0: //編輯聯系人 //1, 游標指向指定的數據 if(cursor.moveToPosition(position)) { //2, 從游標中獲取當前點擊的 Item 對應的 姓名+電話 int id = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); //3, 帶著參數 進入編輯頁面 Intent intent = new Intent(MainActivity.this, EditActivity.class); intent.putExtra("id", id); intent.putExtra("name", name); intent.putExtra("phone", phone); intent.putExtra("isAdd", false); startActivity(intent); } break; case 1: //刪除聯系人 AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this); builder2.setIcon(R.drawable.ic_launcher); builder2.setTitle("提示"); builder2.setMessage("是否確認刪除?"); builder2.setNegativeButton("取消", null); builder2.setPositiveButton("確定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //1, 游標移動到指定的位置 if(cursor.moveToPosition(position)) { //2, 獲取當前游標指向的 ID int id = cursor.getInt(cursor.getColumnIndex("_id")); //從數據庫中刪除數據 dbService.delete(id); //把游標創建的方法再次執行一次 //cursor.requery(); setListAdapter(); } } }); builder2.show(); break; } } }); builder.show(); } }); } /** * 獲取數據源 設置適配器 */ private void setListAdapter() { //數據源 cursor = dbService.getUsers(); //適配器 adapter = new SimpleCursorAdapter(this, R.layout.item_lv, cursor, new String[]{"name","phone"}, new int[]{R.id.name,R.id.phone}, SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); //設置適配器 lv.setAdapter(adapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { // 加載菜單布局 getMenuInflater().inflate(R.menu.main,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_adduser: Intent intent = new Intent(MainActivity.this, EditActivity.class); intent.putExtra("isAdd", true); startActivity(intent); break; } return super.onOptionsItemSelected(item); } }EditActivity 負責新增與編輯聯系人:
package com.qf.day13_phonebook; import com.qf.day13_phonebook.db.DbService; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class EditActivity extends Activity { private EditText nameEdit,phoneEdit; private boolean isAdd; private DbService dbService; private int id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); nameEdit = (EditText) findViewById(R.id.name_edit); phoneEdit = (EditText) findViewById(R.id.phone_edit); //接收傳入的參數 Intent intent = getIntent(); isAdd = intent.getBooleanExtra("isAdd", true); if(!isAdd) { id = intent.getIntExtra("id", 0); String name = intent.getStringExtra("name"); String phone = intent.getStringExtra("phone"); nameEdit.setText(name); phoneEdit.setText(phone); } //設置 Activity 標題 if(isAdd) { setTitle("添加聯系人"); }else{ setTitle("編輯聯系人"); } dbService = new DbService(this); } public void submit(View v) { String name = nameEdit.getText().toString().trim(); String phone = phoneEdit.getText().toString().trim(); if(isAdd) { dbService.insertUsers(name,phone); } else{ dbService.updateUsers(id,name,phone); } finish(); } }DbOperHelper 繼承 SQLiteOpenHelper,負責建表與版本更新:
package com.qf.day13_phonebook.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DbOperHelper extends SQLiteOpenHelper { public DbOperHelper(Context context) { super(context, "phone_book", null, 1); // TODO Auto-generated constructor stub } //數據庫創建時執行一次 在後台後連接數據庫 @Override public void onCreate(SQLiteDatabase db) { //初始化表 db.execSQL("create table if not exists users(_id integer primary key autoincrement,name,phone)"); db.execSQL("insert into users(name,phone) values('張三','153110120')"); db.execSQL("insert into users(name,phone) values('李四','153120119')"); db.execSQL("insert into users(name,phone) values('王五','153110911')"); db.execSQL("insert into users(name,phone) values('趙六','153110114')"); } //版本更新時執行 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }DbService 是對數據庫操作的封裝類:
package com.qf.day13_phonebook.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * 操作數據庫的封裝類 * * @author Administrator * */ public class DbService { private Context context; private DbOperHelper dbOperHelper; public DbService(Context context) { this.context = context; dbOperHelper = new DbOperHelper(context); } //得到聯系表中的所有數據 public Cursor getUsers() { //1, 打開連接 SQLiteDatabase db = dbOperHelper.getReadableDatabase(); //2, 查詢數據 return db.rawQuery("select * from users", null); } //添加聯系人 public void insertUsers(String name, String phone) { //1, 打開連接 SQLiteDatabase db = dbOperHelper.getWritableDatabase(); //2, 插入數據 ContentValues values = new ContentValues(); values.put("name", name); values.put("phone", phone); db.insert("users", null, values); } //編輯聯系人 public void updateUsers(int id, String name, String phone) { //1, 打開連接 SQLiteDatabase db = dbOperHelper.getWritableDatabase(); //2, 修改數據 ContentValues values = new ContentValues(); values.put("name", name); values.put("phone", phone); db.update("users", values, "_id="+id, null); //db.update("users", values, "_id=?", new String[]{id+""}); } //刪除聯系人 public void delete(int id) { //打開連接 SQLiteDatabase db = dbOperHelper.getWritableDatabase(); //刪除數據 db.execSQL("delete from users where _id="+id); } }mainactivity 布局:
edit activity 布局:
item_lv 布局:
補充幾個常用的游標方法:
boolean cursor.moveToLast():移動到最後一條並判斷是否存在;
boolean cursor.moveToPosition():移動到某一條並判斷是否存在;
int cursor.getCount():得到游標中數據的數量。
取值時,可用 cursor.getString(列的編號)(列編號從 0 開始)獲取內容,也可用 cursor.getColumnIndex("字段名稱") 根據列名得到列編號。
這是一個聯系人存儲的小 demo,運行效果如下:

透過這個案例,我們把建表、增刪改查、游標遍歷與界面聯動串成了一條完整的數據存儲鏈路。
Android 打包與簽名全解:keytool、jarsigner、zipalign 與 Eclipse 導出
最省事的取包方式 只要運行過項目,工作目錄的 bin 文件夾下就會生成與項目同名的 apk。這種包默認已用 debug 用戶簽名,可以直接安裝調試,但不適合發布。 一、
Android Activity 核心概念整理:生命週期、任務堆疊與 Intent 匹配
Activity 是 Android 四大元件之一,也是使用者最直接接觸到的應用程式介面。它不僅負責顯示畫面,還承載著各種 UI 元件,因此常被視為畫面與控制件的容器。
Android Otto 事件總線框架入門:用於解耦元件溝通
這次要介紹的是 Otto——Android 上被廣泛使用的事件總線(EventBus)框架,由 Square 出品。官網:https://square.github.io
Android 加載網絡 GIF 完整解決方案:緩存、進度與同步一次搞定
前言 加載並顯示 GIF 是 App 中很常見的需求。像加載普通圖片一樣,一個完善的方案大致要滿足以下幾點: 1、自動將 GIF 下載到本地作為緩存,同一 url 第二次