欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android利用listview控件操作SQLite数据库实例

程序员文章站 2023-08-21 22:38:27
在本实例中,首先我们利用sqliteopenhelper类建立一个数据库,并写好增、删、查等方法,通过simplecursoradapter连接listview实现数据库的...

在本实例中,首先我们利用sqliteopenhelper类建立一个数据库,并写好增、删、查等方法,通过simplecursoradapter连接listview实现数据库的增加、查询以及长按删除的功能。

Android利用listview控件操作SQLite数据库实例

首先,我们先认识一下什么是sqliteopenhelper类。

android为了操作sqlite数据库,提供了sqlitedatabase类,其内封装了insert 、delete、update 、query 、执行sql命令等操作。同时又为sqlitedatabase提供了一个辅助类,sqliteopenhelper。它提供了两个重要的方法,分别是:

oncreate(sqlitedatabase db):用户初次使用软件时生成数据库,一旦数据库存在则不会调用此方法。函数是在第一次创建数据库的时候执行的,仅仅生成databasehelper对(sqliteopenhelper类型)的时候是不会调用该函数的,而只有当调用databasehelper对象的getreadabledatabase时或者是调用了getwritabledatabase时,如果是第一次创建数据库,那么就一定会调用oncreate()函数。

onupgrade(sqlitedatabase db,int oldversion,int vewversion):用于升级软件时更新数据库表结构,如增加表、列字段等操作。

实现了这两个方法,就可以用它的getwritabledatabase()和getreadabledatabase()来获得数据库(sqlitedatabase 对象)。

如果用户需要升级数据库表结构,需要主动调用onupgrade(sqlitedatabase db,int oldversion,int vewversion),传入一个新的版本的号。

建立一个新数据库的代码如下:

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");
  }   
}

接下来我们建立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;  //数据库帮助类
  private edittext et_tittle;          //输入新闻标题
  private edittext et_content;        //输入新闻内容
  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);       //创建一个名为“news”的数据库

    //初始化控件
    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); 
      // 设置长按事件 


  }

  /*
   * 按钮点击事件
   * 通过判断被点击的组件, 执行不同的操作
   */
  public void onclick(view view) {
    int id = view.getid();
    if(id==r.id.bt_add) 
     insertnews();

    else if(id== r.id.bt_query)
        querynews();

    }

  /*
   * 刷新数据库列表显示
   * 1. 关联simplecursoradapter与数据库表, 获取数据库表中的最新数据
   * 2. 将最新的simplecursoradapter设置给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);
  }

  /*
   * 插入新闻数据
   * 1. 从edittext组件中获取新闻的标题 和 新闻内容
   * 2. 获取数据库并从将 新闻标题 和 内容 插入到数据库中
   * 3. 重新查询数据库 获得cursor对象
   * 4. 根据cursor对象创建simplecursoradapter对象
   * 5. 将simplecursoradapter设置给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
  }

  /*
   * 删除新闻数据
   * 根据_id删除指定数据,并进行刷新
   */
  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(), "删除数据库失败", 
           toast.length_long).show(); 
       return false; 
     } 
     return true; 
   } 



  //长按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("删除当前数据") 
             //设置弹出窗口的图式  
            .seticon(android.r.drawable.ic_dialog_info) 
            // 设置弹出窗口的信息  
            .setmessage("确定删除当前记录") 
            .setpositivebutton("是", 
             new dialoginterface.onclicklistener() { 
             public void onclick( dialoginterface dialoginterface, int i) { 
                    // 获取位置索引 
            int mlistpos = info.position; 
                    // 将listview中所有的数据都传入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); 
               // 移除数据   
             } 
             } 
           ) 
        .setnegativebutton("否", 
          new dialoginterface.onclicklistener() { 
           public void onclick( 
             dialoginterface dialoginterface, int i) { 
                    // 什么也没做 

                  } 
                }).show(); 
      } 
    };





  /*
   * 查询新闻
   * 1. 获取要查询的新闻标题 和 新闻内容
   * 2. 查询数据库 获取 cursor, 并将cursor转化为list<map<string, string>>类型的集合
   * 3. 将集合放入bundle, intent开启另一个activity, 将bundle放入intent对象, 跳转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);  
  }

  /*
   * 返回一个arraylist集合, 这个集合中每个元素是一个map集合, 每个map集合有两个元素
   * 解析cursor对象 : 
   * 1. cursor光标向下移动一格; 
   * 2. 创建一个hashmap对象
   * 3. 使用 cursor.getstring(列标号)获取该行中某列值, 将这个值放入map中
   * 4. 将map对象放入
   */
  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();
    //释放数据库资源
    if(helper !=null)
      helper.close();
  }
}

新建一个activity用来显示查询的结果:

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);

    //设置布局文件
    setcontentview(r.layout.news_search_result);
    //初始化组件
    listview = (listview) findviewbyid(r.id.lv_search_result);
    //获取跳转到该activity的intent对象
    intent intent = getintent();
    //获取intent对象所携带的数据
    bundle bundle = intent.getextras();
    //从bundle中取出list<map<string,string>>数据
    @suppresswarnings("unchecked")
    list<map<string, string>> list = (list<map<string, string>>)bundle.getserializable("news");

    simpleadapter adapter = new simpleadapter(
        getapplicationcontext(),   //上下文对象
        list,             //数据源
        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="新闻标题" />

  <edittext 
    android:id="@+id/et_news_tittle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleline="true"
    android:hint="点击此处输入新闻标题"/>

  <textview
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="新闻内容" />

  <edittext 
    android:id="@+id/et_news_content"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:lines="2"
    android:hint="点击此处输入新闻内容"/>

  <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>

查询结果页面布局文件:

<?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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。