Android利用listview控件操作SQLite數(shù)據(jù)庫(kù)實(shí)例
在本實(shí)例中,首先我們利用SQLiteOpenHelper類建立一個(gè)數(shù)據(jù)庫(kù),并寫好增、刪、查等方法,通過(guò)SimpleCursorAdapter連接listview實(shí)現(xiàn)數(shù)據(jù)庫(kù)的增加、查詢以及長(zhǎng)按刪除的功能。

首先,我們先認(rèn)識(shí)一下什么是SQLiteOpenHelper類。
Android為了操作SQlite數(shù)據(jù)庫(kù),提供了SQLiteDatabase類,其內(nèi)封裝了insert 、delete、update 、query 、執(zhí)行SQL命令等操作。同時(shí)又為SQLiteDatabase提供了一個(gè)輔助類,SQLiteOpenHelper。它提供了兩個(gè)重要的方法,分別是:
onCreate(SQLiteDatabase db):用戶初次使用軟件時(shí)生成數(shù)據(jù)庫(kù),一旦數(shù)據(jù)庫(kù)存在則不會(huì)調(diào)用此方法。函數(shù)是在第一次創(chuàng)建數(shù)據(jù)庫(kù)的時(shí)候執(zhí)行的,僅僅生成DataBaseHelper對(duì)(SQLiteOpenHelper類型)的時(shí)候是不會(huì)調(diào)用該函數(shù)的,而只有當(dāng)調(diào)用DataBaseHelper對(duì)象的getReadableDataBase時(shí)或者是調(diào)用了getWritableDataBase時(shí),如果是第一次創(chuàng)建數(shù)據(jù)庫(kù),那么就一定會(huì)調(diào)用onCreate()函數(shù)。
onUpgrade(SQLiteDatabase db,int oldVersion,int vewVersion):用于升級(jí)軟件時(shí)更新數(shù)據(jù)庫(kù)表結(jié)構(gòu),如增加表、列字段等操作。
實(shí)現(xiàn)了這兩個(gè)方法,就可以用它的getWritableDatabase()和getReadableDatabase()來(lái)獲得數(shù)據(jù)庫(kù)(SQLiteDatabase 對(duì)象)。
如果用戶需要升級(jí)數(shù)據(jù)庫(kù)表結(jié)構(gòu),需要主動(dòng)調(diào)用onUpgrade(SQLiteDatabase db,int oldVersion,int vewVersion),傳入一個(gè)新的版本的號(hào)。
建立一個(gè)新數(shù)據(jù)庫(kù)的代碼如下:
package com.example.listview_sqlite_xu;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class NewsSearchDatabaseHelper extends SQLiteOpenHelper {
final String SQL_CREATE_TABLE = "create table news_table (" +
"_id integer primary key autoincrement, " +
"news_tittle varchar(50), " +
"news_content varchar(5000))";
public NewsSearchDatabaseHelper(Context context, String name, int version) {
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("call update");
}
}
接下來(lái)我們建立MainActivity:
package com.example.listview_sqlite_xu;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
private NewsSearchDatabaseHelper helper; //數(shù)據(jù)庫(kù)幫助類
private EditText et_tittle; //輸入新聞標(biāo)題
private EditText et_content; //輸入新聞內(nèi)容
private ListView listView; //顯示新聞列表
ArrayList<HashMap<String, Object>> listData; // key-value
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new NewsSearchDatabaseHelper(getApplicationContext(), "news", 1); //創(chuàng)建一個(gè)名為“news”的數(shù)據(jù)庫(kù)
//初始化控件
et_tittle = (EditText) findViewById(R.id.et_news_tittle);
et_content = (EditText) findViewById(R.id.et_news_content);
listView = (ListView) findViewById(R.id.lv_news);
listView.setOnCreateContextMenuListener(listviewLongPress);
// 設(shè)置長(zhǎng)按事件
}
/*
* 按鈕點(diǎn)擊事件
* 通過(guò)判斷被點(diǎn)擊的組件, 執(zhí)行不同的操作
*/
public void onClick(View view) {
int id = view.getId();
if(id==R.id.bt_add)
insertNews();
else if(id== R.id.bt_query)
queryNews();
}
/*
* 刷新數(shù)據(jù)庫(kù)列表顯示
* 1. 關(guān)聯(lián)SimpleCursorAdapter與數(shù)據(jù)庫(kù)表, 獲取數(shù)據(jù)庫(kù)表中的最新數(shù)據(jù)
* 2. 將最新的SimpleCursorAdapter設(shè)置給ListView
*/
private void inflateListView(Cursor cursor) {
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.item, cursor, new String[]{"news_tittle", "news_content"}, new int[]{R.id.tittle, R.id.content},1);
listView.setAdapter(cursorAdapter);
}
/*
* 插入新聞數(shù)據(jù)
* 1. 從EditText組件中獲取新聞的標(biāo)題 和 新聞內(nèi)容
* 2. 獲取數(shù)據(jù)庫(kù)并從將 新聞標(biāo)題 和 內(nèi)容 插入到數(shù)據(jù)庫(kù)中
* 3. 重新查詢數(shù)據(jù)庫(kù) 獲得Cursor對(duì)象
* 4. 根據(jù)cursor對(duì)象創(chuàng)建SimpleCursorAdapter對(duì)象
* 5. 將SimpleCursorAdapter設(shè)置給ListView, 顯示新聞列表
*/
private void insertNews() {
String tittle = et_tittle.getText().toString();
String content = et_content.getText().toString();
helper.getReadableDatabase().execSQL("insert into news_table values(null, ?, ?)", new String[]{tittle, content});
Cursor cursor = helper.getReadableDatabase().rawQuery("select * from news_table", null);
inflateListView(cursor); //刷新listview
}
/*
* 刪除新聞數(shù)據(jù)
* 根據(jù)_id刪除指定數(shù)據(jù),并進(jìn)行刷新
*/
private boolean deleteNews(int _id) {
String whereClause = "_id=?";
String[] whereArgs = new String[] { String.valueOf(_id) };
try{
helper.getReadableDatabase().delete("news_table", whereClause,whereArgs);
Cursor cursor = helper.getWritableDatabase().rawQuery("select * from news_table", null);
inflateListView(cursor);
}catch (SQLException e) {
Toast.makeText(getApplicationContext(), "刪除數(shù)據(jù)庫(kù)失敗",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//長(zhǎng)按listview刪除item
OnCreateContextMenuListener listviewLongPress = new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
new AlertDialog.Builder(MainActivity.this)
// 彈出窗口的最上頭文字
.setTitle("刪除當(dāng)前數(shù)據(jù)")
//設(shè)置彈出窗口的圖式
.setIcon(android.R.drawable.ic_dialog_info)
// 設(shè)置彈出窗口的信息
.setMessage("確定刪除當(dāng)前記錄")
.setPositiveButton("是",
new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialoginterface, int i) {
// 獲取位置索引
int mListPos = info.position;
// 將listview中所有的數(shù)據(jù)都傳入hashmap-listData中
Cursor c = helper.getReadableDatabase().rawQuery("select * from news_table", null);
int columnsSize = c.getColumnCount();
listData = new ArrayList<HashMap<String, Object>>();
while (c.moveToNext()) {
HashMap<String, Object> map = new HashMap<String, Object>();
for (int j = 0; j < columnsSize; j++) {
map.put("_id", c.getString(0));
map.put("news_tittle", c.getString(1));
map.put("news_content", c.getString(2));
}
listData.add(map);
}
HashMap<String, Object> map = listData .get(mListPos);
// 獲取id
int id = Integer.valueOf((map.get("_id").toString()));
deleteNews(id);
// 移除數(shù)據(jù)
}
}
)
.setNegativeButton("否",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
// 什么也沒(méi)做
}
}).show();
}
};
/*
* 查詢新聞
* 1. 獲取要查詢的新聞標(biāo)題 和 新聞內(nèi)容
* 2. 查詢數(shù)據(jù)庫(kù) 獲取 Cursor, 并將Cursor轉(zhuǎn)化為L(zhǎng)ist<Map<String, String>>類型的集合
* 3. 將集合放入bundle, Intent開(kāi)啟另一個(gè)Activity, 將bundle放入intent對(duì)象, 跳轉(zhuǎn)Activity
*
*/
private void queryNews() {
String tittle = et_tittle.getText().toString();
String content = et_content.getText().toString();
Cursor cursor = helper.getReadableDatabase().rawQuery(
"select * from news_table where news_tittle like ? and news_content like ?",
new String[]{"%" + tittle + "%", "%" + content + "%"});
Bundle bundle = new Bundle();
bundle.putSerializable("news", cursor2list(cursor));
Intent intent = new Intent(this, SearchResultActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
/*
* 返回一個(gè)ArrayList集合, 這個(gè)集合中每個(gè)元素是一個(gè)Map集合, 每個(gè)Map集合有兩個(gè)元素
* 解析Cursor對(duì)象 :
* 1. cursor光標(biāo)向下移動(dòng)一格;
* 2. 創(chuàng)建一個(gè)HashMap對(duì)象
* 3. 使用 cursor.getString(列標(biāo)號(hào))獲取該行中某列值, 將這個(gè)值放入map中
* 4. 將Map對(duì)象放入
*/
private ArrayList<Map<String, String>> cursor2list(Cursor cursor) {
ArrayList<Map<String, String>> list = new ArrayList<Map<String,String>>();
//遍歷Cursor
while(cursor.moveToNext()){
Map<String, String> map = new HashMap<String, String>();
map.put("tittle", cursor.getString(1));
map.put("content", cursor.getString(2));
list.add(map);
}
return list;
}
@Override
protected void onDestroy() {
super.onDestroy();
//釋放數(shù)據(jù)庫(kù)資源
if(helper !=null)
helper.close();
}
}
新建一個(gè)Activity用來(lái)顯示查詢的結(jié)果:
package com.example.listview_sqlite_xu;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SearchResultActivity extends Activity {
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//設(shè)置布局文件
setContentView(R.layout.news_search_result);
//初始化組件
listView = (ListView) findViewById(R.id.lv_search_result);
//獲取跳轉(zhuǎn)到該Activity的intent對(duì)象
Intent intent = getIntent();
//獲取Intent對(duì)象所攜帶的數(shù)據(jù)
Bundle bundle = intent.getExtras();
//從Bundle中取出List<Map<String,String>>數(shù)據(jù)
@SuppressWarnings("unchecked")
List<Map<String, String>> list = (List<Map<String, String>>)bundle.getSerializable("news");
SimpleAdapter adapter = new SimpleAdapter(
getApplicationContext(), //上下文對(duì)象
list, //數(shù)據(jù)源
R.layout.item, //List顯示布局
new String[]{"tittle", "content"}, //List中map的鍵值
new int[]{R.id.tittle, R.id.content}); //填充到的布局文件
listView.setAdapter(adapter);
}
}
main_activity的布局文件
<LinearLayout 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=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新聞標(biāo)題" />
<EditText
android:id="@+id/et_news_tittle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:hint="點(diǎn)擊此處輸入新聞標(biāo)題"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="新聞內(nèi)容" />
<EditText
android:id="@+id/et_news_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="2"
android:hint="點(diǎn)擊此處輸入新聞內(nèi)容"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal">
<Button
android:id="@+id/bt_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="添加新聞" />
<Button
android:id="@+id/bt_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="查找新聞" />
</LinearLayout>
<ListView
android:id="@+id/lv_news"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
listview的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tittle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:textColor="#CC0000"
/>
<TextView
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="10dp"
android:textColor="#00FF00"/>
</LinearLayout>
查詢結(jié)果頁(yè)面布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lv_search_result"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android控件ViewFlipper仿淘寶頭條垂直滾動(dòng)廣告條
這篇文章主要為大家詳細(xì)介紹了Android控件ViewFlipper仿淘寶頭條垂直滾動(dòng)廣告條,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-05-05
Android實(shí)現(xiàn)光點(diǎn)模糊漸變的自旋轉(zhuǎn)圓環(huán)特效
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)光點(diǎn)模糊漸變的自旋轉(zhuǎn)圓環(huán)特效,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06
Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載
這篇文章主要介紹了Android編程開(kāi)發(fā)實(shí)現(xiàn)帶進(jìn)度條和百分比的多線程下載,總結(jié)了前面關(guān)于Java多線程下載的技巧,實(shí)例分析了Android實(shí)現(xiàn)帶百分比和進(jìn)度條的多線程下載技巧,需要的朋友可以參考下2015-12-12
Android 簡(jiǎn)單實(shí)現(xiàn)一個(gè)流式布局的示例
本篇文章主要介紹了Android 簡(jiǎn)單實(shí)現(xiàn)一個(gè)流式布局的示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
Android實(shí)現(xiàn)輪播圖無(wú)限循環(huán)效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)輪播圖無(wú)限循環(huán)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-02-02
Android MediaPlayer實(shí)現(xiàn)音樂(lè)播放器實(shí)例代碼
這篇文章主要介紹了Android MediaPlayer實(shí)現(xiàn)音樂(lè)播放器實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下2017-01-01
Android實(shí)現(xiàn)發(fā)送短信功能實(shí)例詳解
這篇文章主要介紹了Android實(shí)現(xiàn)發(fā)送短信功能的方法,結(jié)合實(shí)例形式較為詳細(xì)的分析了Android實(shí)現(xiàn)發(fā)送短信的原理、步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-02-02

