SQLiteOpenHelper

SQLiteOpenHelper是android提供的一个管理数据库的工具类,可用于管理数据库的创建和版本更新。

一般的用法是创建SQLiteOpenHelper的子类,并扩展它的onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db,int oldVersion,newVersion)方法。

SQLiteOpenHelper包含如下常用方法:

sychronized SQLiteDatabase getReadableDatabase() 以读写的方式打开数据库对应的SQLiteDataBase对象
sychronized SQLiteDatabase getWriteableDataBase() 以写的方式打开数据库对应的SQLiteDataBase对象
abstract void onCreate(SQLiteDatabase db) 当第一次创建数据库时回调该方法
abstract void onUpgrade(SQLiteDatabase db,int oldVersion,newVersion) 当数据库版本更新时回调该方法
sychronized void close() 关闭所有打开的SQLiteDatabase

实例如下:

布局文件==》main
<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:orientation="vertical"
tools:context=".MainActivity" > <EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <EditText
android:id="@+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:id="@+id/btnInsert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="添加生词" /> <EditText
android:id="@+id/edit3"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <Button
android:id="@+id/btnQuery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="查询" /> </LinearLayout>
result.xml==>
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent" /> <EditText
android:id="@+id/word"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> <EditText
android:id="@+id/detial"
android:layout_width="match_parent"
android:layout_height="wrap_content" /> </LinearLayout>
代码实现==》
package com.example.mysqlite2; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log; public class MyDatabaseHelper extends SQLiteOpenHelper
{
final String CREATE_TABLE_SQL = "create table dict(_id integer primary key autoincrement,word,detial)"; public MyDatabaseHelper(Context context, String name, int version)
{
super(context, name, null, version);
Log.i("swg", "-----------MyDatabaseHelper------------");
} @Override
public void onCreate(SQLiteDatabase db)
{
// 第一个使用数据库时自动见表
db.execSQL(CREATE_TABLE_SQL);
Log.i("swg", "-----------创建表成功------------");
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
System.out
.println("-----------onUpgrade----------" + oldVersion + "-------->" + newVersion);
} } package com.example.mysqlite2; import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map; import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity
{
MyDatabaseHelper dbHelper;
EditText edit1;
EditText edit2;
EditText edit3;
String dbName = "test.db3"; @Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 创建MyDatabaseHelper对象,指定数据库版本为1,此处使用相对路径
// 数据库文件会自动保存在程序的数据文件夹下的databases目录下
dbHelper = new MyDatabaseHelper(this, dbName, 1); edit1 = (EditText) this.findViewById(R.id.edit1);
edit2 = (EditText) this.findViewById(R.id.edit2);
edit3 = (EditText) this.findViewById(R.id.edit3);
Button btnInsert = (Button) this.findViewById(R.id.btnInsert);
Button btnQuery = (Button) this.findViewById(R.id.btnQuery);
btnInsert.setOnClickListener(new MyButtonOnClick());
btnQuery.setOnClickListener(new MyButtonOnClick());
} private class MyButtonOnClick implements OnClickListener
{
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btnInsert:
String word = edit1.getText().toString();
String detial = edit2.getText().toString(); Log.i("swg", "insert content==" + word + "=========" + detial);
// 插入生词记录
insertData(dbHelper.getReadableDatabase(), word, detial);
Toast.makeText(MainActivity.this, "添加生词成功", Toast.LENGTH_LONG).show();
break;
case R.id.btnQuery:
String key = edit3.getText().toString();
Log.i("swg", "key==" + key);
// 执行查询
String sql = "select * from dict where word like ? or detial like ? ";
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(sql,
new String[] { "%" + key + "%", "%" + key + "%" }); Bundle data = new Bundle();
data.putSerializable("data", convertCursorToList(cursor)); Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtras(data);
startActivity(intent);
break;
}
} private ArrayList<Map<String, String>> convertCursorToList(Cursor cursor)
{
ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
while (cursor.moveToNext())
{
Map<String, String> map = new HashMap<String, String>();
map.put("word", cursor.getString(1));
map.put("detial", cursor.getString(2));
result.add(map);
}
return result;
} private void insertData(SQLiteDatabase db, String word, String detial)
{
String sql = "insert into dict values (null,?,?)";
db.execSQL(sql, new String[] { word, detial });
} } @Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
} @Override
protected void onDestroy()
{
super.onDestroy();
// 退出程序时关闭MyDatabaseHelper里的SQLitedatabase
if (dbHelper != null)
dbHelper.close();
} } package com.example.mysqlite2; import java.util.List;
import java.util.Map; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter; public class ResultActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.result); ListView lv = (ListView) this.findViewById(R.id.lv);
Intent intent = getIntent();
Bundle data = intent.getExtras();
@SuppressWarnings("unchecked")
List<Map<String, String>> list = (List<Map<String, String>>) data.getSerializable("data");
// 将list封装成SimpleAdapter
SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this, list, R.layout.result,
new String[] { "word", "detial" }, new int[] { R.id.word, R.id.detial });
int count = adapter.getCount();
Log.i("swg", "查到" + count + "条");
lv.setAdapter(adapter);
} }

注意:AndroidMainfest.xml需要添加==》<activity android:name="com.example.mysqlite2.ResultActivity" android:theme="@android:style/Theme.Dialog"/>

运行效果:

注意:android实现系统自带样式如下方式:

android:theme="@android:style/Theme.Dialog" : Activity显示为对话框模式

android:theme="@android:style/Theme.NoTitleBar" : 不显示应用程序标题栏

android:theme="@android:style/Theme.NoTitleBar.Fullscreen" : 不显示应用程序标题栏,并全屏

android:theme="Theme.Light ": 背景为白色

android:theme="Theme.Light.NoTitleBar" : 白色背景并无标题栏

android:theme="Theme.Light.NoTitleBar.Fullscreen" : 白色背景,无标题栏,全屏

android:theme="Theme.Black" : 背景黑色

android:theme="Theme.Black.NoTitleBar" : 黑色背景并无标题栏

android:theme="Theme.Black.NoTitleBar.Fullscreen" : 黑色背景,无标题栏,全屏

android:theme="Theme.Wallpaper" : 用系统桌面为应用程序背景

android:theme="Theme.Wallpaper.NoTitleBar" : 用系统桌面为应用程序背景,且无标题栏

android:theme="Theme.Wallpaper.NoTitleBar.Fullscreen" : 用系统桌面为应用程序背景,无标题栏,全屏

android:theme="Theme.Translucent : 透明背景

android:theme="Theme.Translucent.NoTitleBar" : 透明背景并无标题

android:theme="Theme.Translucent.NoTitleBar.Fullscreen" : 透明背景并无标题,全屏

android:theme="Theme.Panel ": 面板风格显示

android:theme="Theme.Light.Panel" : 平板风格显示

android学习笔记50——SQLiteOpenHelper、android实现系统自带样式的更多相关文章

  1. Android学习笔记50:使用WebView控件浏览网页

    在Android中,可以使用Webview控件来浏览网页.通过使用该控件,我们可以自制一个简单的浏览器,运行效果如图1所示. 图1 运行效果 1.WebView 在使用WebView控件时,首先需要在 ...

  2. Android学习笔记_51_转android 加载大图片防止内存溢出

    首先来还原一下堆内存溢出的错误.首先在SD卡上放一张照片,分辨率为(3776 X 2520),大小为3.88MB,是我自己用相机拍的一张照片.应用的布局很简单,一个Button一个ImageView, ...

  3. Android学习笔记:对Android应用进行单元测试

     第一步:在AndroidManifest.xml中加入如下两段代码: <manifest xmlns:android="http://schemas.android.com/ap ...

  4. Android学习笔记之:android更新ui的几种经常用法

    Android主线程不能运行耗时操作.我们通常是在子线程中运行耗时操作, 我们在运行完耗时操作后,我们一般能够通过下面几种方式来实现ui界面的更新. 首先是布局文件: <LinearLayout ...

  5. Android学习笔记----解决“com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536”问题

    同时在工程中引入了多个第三方jar包,导致调用的方法数超过了android设定的65536个(DEX 64K problem),进而导致dex无法生成,也就无法生成APK文件. 解决办法如下: 1.谷 ...

  6. Android学习笔记36:使用SQLite方式存储数据

    在Android中一共提供了5种数据存储方式,分别为: (1)Files:通过FileInputStream和FileOutputStream对文件进行操作.具体使用方法可以参阅博文<Andro ...

  7. 【转】 Pro Android学习笔记(七四):HTTP服务(8):使用后台线程AsyncTask

    目录(?)[-] 5秒超时异常 AsyncTask 实现AsyncTask抽象类 对AsyncTask的调用 在哪里运行 其他重要method 文章转载只能用于非商业性质,且不能带有虚拟货币.积分.注 ...

  8. 【转】Pro Android学习笔记(七):了解Content Provider(下上)

    我们通过一个Content Provider小例子进行详细说明.数据源是一个SQLite数据库,名字为books.db,该数据库只含有一个表格,名字为books.表格中含有name,isbn,auth ...

  9. Android学习笔记之Activity详解

    1 理解Activity Activity就是一个包含应用程序界面的窗口,是Android四大组件之一.一个应用程序可以包含零个或多个Activity.一个Activity的生命周期是指从屏幕上显示那 ...

随机推荐

  1. no leveldbjni64-1.8 in java.library.path

    在抽取以太坊Java版本的Trie树部分时,遇到了一个问题: Exception in thread "main" java.lang.UnsatisfiedLinkError: ...

  2. MVP 个人理解2

    根据我的理解,画了个图 这次又看了下 较复杂点的例子. 往往一个项目有多个部份,我们可以按功能分成几个activity, 每个activity有自己的view和数据model,因此也有自己的逻辑 pr ...

  3. 完美实现跨域Iframe高度自适应【Iframe跨域高度自适应解决方案】

    Iframe的强大功能偶就不多说了,它不但被开发人员经常运用,而且黑客们也常常使用它,总之用过的人知道它的强大之处,但是Iframe有个致命的“BUG”就是iframe的高度无法自动适应,这一点让很多 ...

  4. iOS开发UI篇—无限轮播(新闻数据展示)

    iOS开发UI篇—无限轮播(新闻数据展示) 一.实现效果        二.实现步骤 1.前期准备 (1)导入数据转模型的第三方框架MJExtension (2)向项目中添加保存有“新闻”数据的pli ...

  5. 【lattice软核】MICO8流程

    The LatticeMico System software is composed of three bundled applications:  Mico System Builder (MS ...

  6. sprintf函数

    sprintf函数用法举例 #include<stdio.h> int main() { //1.连接字符串 char a1[] = {'A', 'B', 'C', 'D', 'E', ' ...

  7. php dirname(__FILE__) 获取当前文件的绝对路径 (转)

    比如当前文件是放在(d:\www\)下,文件名是test.php. 测试的代码如下: 复制代码 代码如下: <?php echo __FILE__ ; // 取得当前文件的绝对地址,结果:D:\ ...

  8. java堆、栈、堆栈的区别

    1.栈(stack)与堆(heap)都是Java用来在Ram中存放数据的地方.与C++不同,Java自动管理栈和堆,程序员不能直接地设置栈或堆. 2. 栈的优势是,存取速度比堆要快,仅次于直接位于CP ...

  9. GCD的基本知识

    什么是GCD 全称是Grand Central Dispatch,可译为“牛逼的中枢调度器” 纯C语言,提供了非常多强大的函数 GCD的优势 GCD是苹果公司为多核的并行运算提出的解决方案 GCD会自 ...

  10. HDU 4822----其实不会这个题

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=4822 并不会做这个题,题解说是LCA(最近公共祖先),并不懂,说一下我自己的思路吧,虽然没能实现出来. 题 ...