Android整理:SQlite資料庫的使用以及通過listView顯示資料
阿新 • • 發佈:2019-02-05
前言:上個月與同學一起做了一個簡單的Android應用,這段時間正好沒有很多事情所以趁熱整理一下學習到的知識,剛開始學習Android還有很多不懂的地方,繼續努力吧!
作業中需要用到資料庫,當然首選Android集成了的SQLite資料庫。
直接使用資料庫可以這樣:
//開啟或建立test.db資料庫 SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); //建立person表 db.execSQL("CREATE TABLE IF NOT EXISTS person([id] INTEGER PRIMARY KEY, [name] TEXT)"); //查詢 Cursor cursor = db.rawQuery("select * from person where name = " + "'urbain'", null); if(cursor.moveToNext()) { id = Integer.parseInt( cursor.getString(0) ); name = cursor.getString(1); } //更新刪除操作均可用db.execSQL(string)來操作
利用listView顯示資料庫中的資料要加一個adapter,步驟:
1.將Sqlite資料庫的內容查詢出來並放入陣列列表中,形成ListView的資料來源;
2.adapter介面卡繫結資料來源,顯示在ListView item中。
自己寫類DatabaseHelper繼承SQLiteOpenHelper並實現部分資料庫操作:
package com.zkurbain.wenriji; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper{ private static final int VERSION = 1; public DatabaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } public DatabaseHelper(Context context, String name){ this(context, name, VERSION); } public DatabaseHelper(Context context, String name, int version){ this(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { //建立表 String crtWenTable = "CREATE TABLE IF NOT EXISTS [wenti]([wentiHash] INTENGER PRIMARY KEY, [wentiName] TEXT)" ; db.execSQL(crtWenTable); //如果資料庫為空,則預置一些資料 Cursor cursor = db.rawQuery("select * from wenti", null); if( !cursor.moveToNext()){ String[] swen = {"我今天讀書了嗎?", "我明天打算做什麼?", "今天吃啥好吃的?"}; db.beginTransaction(); //開始事務處理 for (String s : swen) { db.execSQL("insert into wenti values(" + s.hashCode() + ", '"+ s +"')"); } db.setTransactionSuccessful(); //設定事務標誌為成功,當結束事務時就會提交事務 db.endTransaction(); //結束事務 } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
在主類中,藉助SimpleAdapter使資料顯示在listView:
package com.zkurbain.wenriji; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleAdapter; public class ChooseWen extends Activity { private ListView listView = null; private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); private SimpleAdapter simpleAdapter = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_choose_wen); listView = (ListView) findViewById(android.R.id.list); simpleAdapter = new SimpleAdapter(this, getdata(), R.layout.list, new String[] { "wentiName" }, new int[] { R.id.wenti }); //listView繫結adapter listView.setAdapter(simpleAdapter); } private List<Map<String, Object>> getdata() { DatabaseHelper dbHelper = new DatabaseHelper(ChooseWen.this, "wenriji.db"); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from wenti", null); // 清空list list.clear(); // 查詢到的資料新增到list集合 while (cursor.moveToNext()) { String wenti = cursor.getString(1); Map<String, Object> map = new HashMap<String, Object>(); map.put("wentiName", wenti); // 獲取name list.add(map); } return list; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.choose_wen, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } }
下面是XML檔案內容:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.wenriji.wenriji.ChooseWen"
android:id="@+id/activity_choose_wen" >
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" >
<requestFocus />
</ListView>
</RelativeLayout>