欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android利用listview控件操作SQLite數(shù)據(jù)庫實例

 更新時間:2017年04月05日 16:06:56   作者:言丶武  
我們利用SQLiteOpenHelper類建立一個數(shù)據(jù)庫,并寫好增、刪、查等方法,通過SimpleCursorAdapter連接listview實現(xiàn)數(shù)據(jù)庫的增加、查詢以及長按刪除的功能。

在本實例中,首先我們利用SQLiteOpenHelper類建立一個數(shù)據(jù)庫,并寫好增、刪、查等方法,通過SimpleCursorAdapter連接listview實現(xiàn)數(shù)據(jù)庫的增加、查詢以及長按刪除的功能。

首先,我們先認識一下什么是SQLiteOpenHelper類。

Android為了操作SQlite數(shù)據(jù)庫,提供了SQLiteDatabase類,其內(nèi)封裝了insert 、delete、update 、query 、執(zhí)行SQL命令等操作。同時又為SQLiteDatabase提供了一個輔助類,SQLiteOpenHelper。它提供了兩個重要的方法,分別是:

onCreate(SQLiteDatabase db):用戶初次使用軟件時生成數(shù)據(jù)庫,一旦數(shù)據(jù)庫存在則不會調(diào)用此方法。函數(shù)是在第一次創(chuàng)建數(shù)據(jù)庫的時候執(zhí)行的,僅僅生成DataBaseHelper對(SQLiteOpenHelper類型)的時候是不會調(diào)用該函數(shù)的,而只有當調(diào)用DataBaseHelper對象的getReadableDataBase時或者是調(diào)用了getWritableDataBase時,如果是第一次創(chuàng)建數(shù)據(jù)庫,那么就一定會調(diào)用onCreate()函數(shù)。

onUpgrade(SQLiteDatabase db,int oldVersion,int vewVersion):用于升級軟件時更新數(shù)據(jù)庫表結(jié)構(gòu),如增加表、列字段等操作。

實現(xiàn)了這兩個方法,就可以用它的getWritableDatabase()和getReadableDatabase()來獲得數(shù)據(jù)庫(SQLiteDatabase 對象)。

如果用戶需要升級數(shù)據(jù)庫表結(jié)構(gòu),需要主動調(diào)用onUpgrade(SQLiteDatabase db,int oldVersion,int vewVersion),傳入一個新的版本的號。

建立一個新數(shù)據(jù)庫的代碼如下:

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;  //數(shù)據(jù)庫幫助類
  private EditText et_tittle;          //輸入新聞標題
  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)建一個名為“news”的數(shù)據(jù)庫

    //初始化控件
    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í)行不同的操作
   */
  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ù)庫列表顯示
   * 1. 關(guān)聯(lián)SimpleCursorAdapter與數(shù)據(jù)庫表, 獲取數(shù)據(jù)庫表中的最新數(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組件中獲取新聞的標題 和 新聞內(nèi)容
   * 2. 獲取數(shù)據(jù)庫并從將 新聞標題 和 內(nèi)容 插入到數(shù)據(jù)庫中
   * 3. 重新查詢數(shù)據(jù)庫 獲得Cursor對象
   * 4. 根據(jù)cursor對象創(chuàng)建SimpleCursorAdapter對象
   * 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ù),并進行刷新
   */
  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ù)庫失敗", 
           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("刪除當前數(shù)據(jù)") 
             //設(shè)置彈出窗口的圖式  
            .setIcon(android.R.drawable.ic_dialog_info) 
            // 設(shè)置彈出窗口的信息  
            .setMessage("確定刪除當前記錄") 
            .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) { 
                    // 什么也沒做 

                  } 
                }).show(); 
      } 
    };





  /*
   * 查詢新聞
   * 1. 獲取要查詢的新聞標題 和 新聞內(nèi)容
   * 2. 查詢數(shù)據(jù)庫 獲取 Cursor, 并將Cursor轉(zhuǎn)化為List<Map<String, String>>類型的集合
   * 3. 將集合放入bundle, Intent開啟另一個Activity, 將bundle放入intent對象, 跳轉(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);  
  }

  /*
   * 返回一個ArrayList集合, 這個集合中每個元素是一個Map集合, 每個Map集合有兩個元素
   * 解析Cursor對象 : 
   * 1. cursor光標向下移動一格; 
   * 2. 創(chuàng)建一個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();
    //釋放數(shù)據(jù)庫資源
    if(helper !=null)
      helper.close();
  }
}

新建一個Activity用來顯示查詢的結(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對象
    Intent intent = getIntent();
    //獲取Intent對象所攜帶的數(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(),   //上下文對象
        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="新聞標題" />

  <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="新聞內(nèi)容" />

  <EditText 
    android:id="@+id/et_news_content"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:lines="2"
    android:hint="點擊此處輸入新聞內(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é)果頁面布局文件:

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

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Android多渠道打包的方法步驟

    Android多渠道打包的方法步驟

    本篇文章主要介紹了Android多渠道打包的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Android檢測手機多點觸摸點數(shù)的方法

    Android檢測手機多點觸摸點數(shù)的方法

    這篇文章主要為大家詳細介紹了Android檢測手機多點觸摸點數(shù)的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-05-05
  • 簡單掌握Android Widget桌面小部件的創(chuàng)建步驟

    簡單掌握Android Widget桌面小部件的創(chuàng)建步驟

    這篇文章主要介紹了簡單掌握Android Widget桌面小部件的創(chuàng)建步驟,Widget一般采用web前端技術(shù)進行開發(fā),需要的朋友可以參考下
    2016-03-03
  • flutter簡單使用案例

    flutter簡單使用案例

    這篇文章主要介紹了使用Flutter短視頻上滑翻頁效果,本篇介紹了?Flutter的翻頁組件PageView的使用,通過?PageView可以輕松實現(xiàn)類似短視頻的縱向上滑翻頁的效果,也可以實現(xiàn)橫向翻頁效果(如閱讀類軟件),需要的朋友可以參考下
    2023-05-05
  • 最新評論