安卓筆記3--SQLite資料庫和對話方塊,安卓3--sqlite

來源:互聯網
上載者:User

安卓筆記3--SQLite資料庫和對話方塊,安卓3--sqlite


現在介紹一下安卓如何操作資料庫和幾種常見的安卓對話方塊。老規矩,用一張圖來介紹今天的內容。

圖片看不清的話可以右鍵新視窗開啟



一、SQLite資料庫

SQLite,是一款輕量型的資料庫,是遵守 ACID(原子性、一致性、隔離性、持久性)的關聯式資料庫管理系統,多用於嵌入式開發中。

SQLite 資料庫是無類型的,可以向一個 integer 的列中添加一個字串,但它又支援常見的類型比如: NULL, VARCHAR, TEXT, INTEGER, BLOB, CLOB 等

1,建立一個資料庫協助類,用於操作資料庫

創 建 一 個 PersonOpenHelper 類 , 繼 承 SQLiteOpenHelper 抽 象 類 , 重寫onCreate 和 onUpgrade 方法。

public class PersonSQLiteOpenHelper extends SQLiteOpenHelper {/** * 把已知的固定值寫好(資料庫名稱,版本號碼), 外邊只傳一個Context進來就可以初始化該協助類了 * @param context */public PersonSQLiteOpenHelper(Context context){// 轉調4個參數的建構函式this(context, "jin8.db", null, 3);}/** * 建立一個資料庫協助類, 去建立\ 開啟\ 管理 資料庫. * @param context 上下文. * @param name 設定資料庫名稱 * @param factory  CursorFactory 定義一個結果集, 遊標工廠.  * Cursor 遊標(結果集, 儲存了對資料庫的引用, 指標) * 設定為null表示使用系統預設遊標工廠 * @param version 資料庫的版本, 從1開始 >= 1   */public PersonSQLiteOpenHelper(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);}/** * 當資料庫第一次被建立時調用, 這裡進行表結構的建立和初始化. */@Overridepublic void onCreate(SQLiteDatabase db) {System.out.println("PersonSQLiteOpenHelper: onCreate");// 執行建立語句, 建立person表db.execSQL("create table person(_id integer primary key autoincrement, name varchar(20),age integer)");}/** * 資料庫升級時調用, 在這裡做表結構的更新,刪除等操作. */@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {System.out.println("PersonSQLiteOpenHelper: onUpgrade " + "舊版本號碼: " + oldVersion + " 新版本號碼: " + newVersion);if(oldVersion == 2 && newVersion == 3){// 版本從2升級到3, 給person表添加一個balance餘額欄位db.execSQL("alter table person add column balance integer");}}}

2,SQL動作陳述式

public class PersonDAO2 {private PersonSQLiteOpenHelper helper;public PersonDAO2(Context context){helper = new PersonSQLiteOpenHelper(context);}/** * 插入一條資料, 指定名稱和年齡 * @param name * @param age */public void insert(String name, int age) {// 擷取可寫資料庫SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("insert into person (name, age) values (?, ?)", new Object[]{name, age});}/** * 根據指定名稱刪除一條資料 * @param name */public void delete(String name) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("delete from person where name = ?", new Object[]{name});}/** * 修改一條資料, 修改指定人的年齡 * @param name * @param age */public void update(String name, int age) {SQLiteDatabase db = helper.getWritableDatabase();db.execSQL("update person set age = ? where name = ?", new Object[]{age, name});}/** * 查詢一條資料 * @param name */public void querySingleRecord(String nameArg) {SQLiteDatabase db = helper.getReadableDatabase();// ------------------------------------------------- 重點 ↓// 遊標, 對資料庫的引用Cursor cursor = db.rawQuery("select * from person where name = ?", new String[]{nameArg});if(cursor != null && cursor.moveToFirst()){ // 是否能移動到第一個int _id = cursor.getInt(0);String name = cursor.getString(1);int age = cursor.getInt(2);System.out.println("_id: " + _id + " name: " + name + " age: " + age);}// 關閉應用cursor.close();// ------------------------------------------------- 以上 ↑}/** * 查詢所有資料 */public List<Person> queryAll() {SQLiteDatabase db = helper.getReadableDatabase();Cursor cursor = db.rawQuery("select * from person", null);ArrayList<Person> persons = new ArrayList<Person>();if(cursor != null && cursor.getCount() > 0){// 迴圈遍曆// 擷取列數int columnCount = cursor.getColumnCount();System.out.println("columnCount: " + columnCount);while(cursor.moveToNext()){ // 直到下一個沒有資料, 返回false// cursor.getColumnIndex("_id")// 根據列名擷取列的索引int _id = cursor.getInt(cursor.getColumnIndex("_id"));String name = cursor.getString(cursor.getColumnIndex("name"));int age = cursor.getInt(cursor.getColumnIndex("age"));Person person = new Person(_id, name, age);System.out.println(person.toString());persons.add(person);}}cursor.close();return persons;}}



二、對話方塊1,通知對話方塊
public void showNotifyDialog(View view){// 1. 通知對話方塊Builder builder = new AlertDialog.Builder(this);// 設定表徵圖builder.setIcon(android.R.drawable.ic_dialog_alert);// 設定標題builder.setTitle("提醒:");// 設定提醒內容builder.setMessage("當前是移動網路資料, 建議在wifi下觀看, 是否繼續(土豪隨意)");builder.setPositiveButton("確認", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, "確認", 0).show();}});builder.setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, "取消", 0).show();}});builder.setCancelable(false); // 是否可以通過返回鍵 關閉// 建立AlertDialog//AlertDialog dialog = builder.create();//dialog.show();// 直接show();builder.show();}



2,顯示列表對話方塊
public void showListDialog(View view){Builder builder = new AlertDialog.Builder(this);builder.setTitle("選擇語言");String[] strs = new String[]{"java", "c++", "c" , "php", "c#", "c" , "php", "c#"};builder.setItems(strs, new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {System.out.println("which: " + which);}});builder.show();}


3,顯示單選對話方塊
public void showSingleDialog(View view){Builder builder = new AlertDialog.Builder(this);builder.setTitle("選擇性別:");final String[] items = new String[]{"男", "女", "中性", "以前男的女的", "以前是女的男的"};builder.setSingleChoiceItems(items, -1, new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {System.out.println("which: " + which);}});builder.setPositiveButton("確認", null);builder.show();}



4,顯示複選對話方塊
public void showMultiDialog(View view){Builder builder = new AlertDialog.Builder(this);builder.setTitle("選擇興趣愛好:");final String[] items = new String[]{"抽煙", "喝酒", "燙頭", "編程", "泡妞"};final boolean[] checkedItems = new boolean[]{true, false, true ,false, false};builder.setMultiChoiceItems(items,checkedItems , new OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {System.out.println("which: " + which + " isChecked: " + isChecked);checkedItems[which] = isChecked;}});builder.setPositiveButton("確認", null);builder.show();}




5,進度條
public void showProgressDialog(View view){// 顯示一個載入的對話方塊//ProgressDialog.show(this, "提示: ", "正在載入中,請稍後...");final ProgressDialog progressDialog = new ProgressDialog(this);progressDialog.setTitle("提示: ");progressDialog.setMessage("正在載入中...");// 設定樣式為 橫向 的progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMax(100);// 顯示的時候, 會把進度歸零progressDialog.show();new Thread(){public void run() {while(true){SystemClock.sleep(50);//progressDialog.setProgress(i);progressDialog.incrementProgressBy(1);if(progressDialog.getProgress() >= progressDialog.getMax()){progressDialog.dismiss();break;}}};}.start();}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.