直接进入主题~
Android 提供了三种数据存储方式,第一种是文件存储;第二种是SharedPreferences 存储;第三种就是数据库SQLiteDatabase 存储。
文件存储我就不用多说了,而SharedPreferences 可以存取简单的数据(int,double,float.etc),它经常用于数据缓存,因为它读取存储简单。详细可以参见本系列。
今天我们将讲一下SQLiteDatabase 的使用**。** 而掌握SqliteDatabase ,将会我们接下来掌握ContentProvider 打下良好的基石**。**
为了让大家更好的掌握,我们手把手完成该节的Demo 。
第一步:新建一个Android工程,命名为SQLiteDatabaseDemo.
第二步:创建一个新的类BooksDB.java 这个类要继承于android.database.sqlite.SQLiteOpenHelper抽象类,我们要实现其中两个方法:onCreate(),onUpdate.具体代码如下:
package com.android.tutor; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class BooksDB extends SQLiteOpenHelper { private final static String DATABASE\_NAME = "BOOKS.db"; private final static int DATABASE\_VERSION = 1; private final static String TABLE\_NAME = "books\_table"; public final static String BOOK\_ID = "book\_id"; public final static String BOOK\_NAME = "book\_name"; public final static String BOOK\_AUTHOR = "book\_author"; public BooksDB(Context context) { // TODO Auto-generated constructor stub super(context, DATABASE\_NAME, null, DATABASE\_VERSION); } //创建table @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE\_NAME + " (" + BOOK\_ID + " INTEGER primary key autoincrement, " + BOOK\_NAME + " text, "+ BOOK\_AUTHOR +" text);"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE\_NAME; db.execSQL(sql); onCreate(db); } public Cursor select() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db .query(TABLE\_NAME, null, null, null, null, null, null); return cursor; } //增加操作 public long insert(String bookname,String author) { SQLiteDatabase db = this.getWritableDatabase(); /\* ContentValues \*/ ContentValues cv = new ContentValues(); cv.put(BOOK\_NAME, bookname); cv.put(BOOK\_AUTHOR, author); long row = db.insert(TABLE\_NAME, null, cv); return row; } //删除操作 public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String where = BOOK\_ID + " = ?"; String\[\] whereValue ={ Integer.toString(id) }; db.delete(TABLE\_NAME, where, whereValue); } //修改操作 public void update(int id, String bookname,String author) { SQLiteDatabase db = this.getWritableDatabase(); String where = BOOK\_ID + " = ?"; String\[\] whereValue = { Integer.toString(id) }; ContentValues cv = new ContentValues(); cv.put(BOOK\_NAME, bookname); cv.put(BOOK\_AUTHOR, author); db.update(TABLE\_NAME, cv, where, whereValue); } }
第三步:修改main.xml布局如下,由两个EditText和一个ListView组成,代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout\_width="fill\_parent" android:layout\_height="fill\_parent" > <EditText android:id="@+id/bookname" android:layout\_width="fill\_parent" android:layout\_height="wrap\_content" > </EditText> <EditText android:id="@+id/author" android:layout\_width="fill\_parent" android:layout\_height="wrap\_content" > </EditText> <ListView android:id="@+id/bookslist" android:layout\_width="fill\_parent" android:layout\_height="wrap\_content" > </ListView> </LinearLayout>
第四步:修改SQLiteDatabaseDemo.java代码如下:
package com.android.tutor; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class SQLiteDatabaseDemo extends Activity implements AdapterView.OnItemClickListener { private BooksDB mBooksDB; private Cursor mCursor; private EditText BookName; private EditText BookAuthor; private ListView BooksList; private int BOOK\_ID = 0; protected final static int MENU\_ADD = Menu.FIRST; protected final static int MENU\_DELETE = Menu.FIRST + 1; protected final static int MENU\_UPDATE = Menu.FIRST + 2; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setUpViews(); } public void setUpViews(){ mBooksDB = new BooksDB(this); mCursor = mBooksDB.select(); BookName = (EditText)findViewById(R.id.bookname); BookAuthor = (EditText)findViewById(R.id.author); BooksList = (ListView)findViewById(R.id.bookslist); BooksList.setAdapter(new BooksListAdapter(this, mCursor)); BooksList.setOnItemClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU\_ADD, 0, "ADD"); menu.add(Menu.NONE, MENU\_DELETE, 0, "DELETE"); menu.add(Menu.NONE, MENU\_DELETE, 0, "UPDATE"); return true; } public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU\_ADD: add(); break; case MENU\_DELETE: delete(); break; case MENU\_UPDATE: update(); break; } return true; } public void add(){ String bookname = BookName.getText().toString(); String author = BookAuthor.getText().toString(); //书名和作者都不能为空,或者退出 if (bookname.equals("") || author.equals("")){ return; } mBooksDB.insert(bookname, author); mCursor.requery(); BooksList.invalidateViews(); BookName.setText(""); BookAuthor.setText(""); Toast.makeText(this, "Add Successed!", Toast.LENGTH\_SHORT).show(); } public void delete(){ if (BOOK\_ID == 0) { return; } mBooksDB.delete(BOOK\_ID); mCursor.requery(); BooksList.invalidateViews(); BookName.setText(""); BookAuthor.setText(""); Toast.makeText(this, "Delete Successed!", Toast.LENGTH\_SHORT).show(); } public void update(){ String bookname = BookName.getText().toString(); String author = BookAuthor.getText().toString(); //书名和作者都不能为空,或者退出 if (bookname.equals("") || author.equals("")){ return; } mBooksDB.update(BOOK\_ID, bookname, author); mCursor.requery(); BooksList.invalidateViews(); BookName.setText(""); BookAuthor.setText(""); Toast.makeText(this, "Update Successed!", Toast.LENGTH\_SHORT).show(); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mCursor.moveToPosition(position); BOOK\_ID = mCursor.getInt(0); BookName.setText(mCursor.getString(1)); BookAuthor.setText(mCursor.getString(2)); } public class BooksListAdapter extends BaseAdapter{ private Context mContext; private Cursor mCursor; public BooksListAdapter(Context context,Cursor cursor) { mContext = context; mCursor = cursor; } @Override public int getCount() { return mCursor.getCount(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView mTextView = new TextView(mContext); mCursor.moveToPosition(position); mTextView.setText(mCursor.getString(1) + "\_\_\_" + mCursor.getString(2)); return mTextView; } } }
第五步:运行程序效果如下:
第六步:查看我们所建的数据库。有两种方法:第一种用命令查看:adb shell ls data/data/com.android.tutor/databases。
另一种方法是用DDMS查看,在data/data下面对应的应用程序的包名 下会有如下数据库,如图所示:
更多Android进阶指南 可以扫码 解锁 《Android十大板块文档》
1.Android车载应用开发系统学习指南(附项目实战)
2.Android Framework学习指南,助力成为系统级开发高手
3.2023最新Android中高级面试题汇总+解析,告别零offer
4.企业级Android音视频开发学习路线+项目实战(附源码)
5.Android Jetpack从入门到精通,构建高质量UI界面
6.Flutter技术解析与实战,跨平台首要之选
7.Kotlin从入门到实战,全方面提升架构基础
8.高级Android插件化与组件化(含实战教程和源码)
9.Android 性能优化实战+360°全方面性能调优
10.Android零基础入门到精通,高手进阶之路
敲代码不易,关注一下吧。ღ( ´・ᴗ・` ) 🤔