Android系统集成了一个轻量级的数据库:SQlite。SQlite不像Oracle、MySQl数据库那样需要安装、启动服务器进程,SQLite数据库只是一个文件

实例1:向数据库里插入数据

主界面:

由两个输入框和一个按钮,以及一个ListView组成
在输入框输入数据,点击按钮发送,数据会送到SQLite中并且在ListView中显示出来

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="2"
/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发送"
/>
<ListView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

ListView用的样式Line.xml界面:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/my_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="120dp"
/>
<EditText
android:id="@+id/my_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

Java代码:

public class MainActivity extends Activity{
SQLiteDatabase db;
Button bn = null;
ListView listView;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建或打开数据库
db = SQLiteDatabase.openOrCreateDatabase(
this.getFilesDir().toString() + "/my.db3", null);
listView = (ListView)findViewById(R.id.show);
bn = (Button) findViewById(R.id.ok);
bn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title = ((EditText)findViewById(R.id.title)).getText().toString();
String content = ((EditText)findViewById(R.id.content)).getText().toString();
try {
insertData(db, title, content);
Cursor cursor = db.rawQuery("select * from news_inf", null);
inflateList(cursor);
}catch (SQLiteException se){
db.execSQL("create table news_inf(_id integer"
+ " primary key autoincrement,"
+ " news_title varchar(50),"
+ " news_content varchar(255))");
insertData(db, title,content);
Cursor cursor = db.rawQuery("select * from news_inf"
, null);
inflateList(cursor);
}
}
});
}
private void insertData(SQLiteDatabase db, String title, String content){
//执行插入语句
db.execSQL("insert into news_inf values(null , ? , ?)",
new String[] {title, content });
}
private void inflateList(Cursor cursor){
//填充SimpleCursorAdapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this,
R.layout.line, cursor,
new String[] { "news_title", "news_content" }
, new int[] {R.id.my_title, R.id.my_content},
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(adapter);
}
public void onDestroy(){
super.onDestroy();
//退出程序时关闭SQLiteDatabase
if (db != null && db.isOpen()){
db.close();
}
}
}

上一个例子中在判断底层数据库是否包含newsinf数据表时使用了try,catch
也就是先尝试插入记录如果根据抛出异常,就创建news_inf数据表,再插入记录.
这样的方式其实有些繁琐,使用Android提供的SQliteOpenHelper能够处理这个问题

实例2:英语单词本

先创建SQLiteOpenHelper的子类,代码如下:

public class MyDatabaseHelper extends SQLiteOpenHelper{
final String CREATE_TABLE_SQL =
"create table dict(_id integer primary " +
"key autoincrement , word , detail)";
public MyDatabaseHelper(Context context, String name, int version){
super(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
//第一次使用数据库时自动建表
db.execSQL(CREATE_TABLE_SQL);
} @Override
//用于更新数据库时,打印一条提示的消息
// oldversion与newVersion为数据库的旧版本与新版本
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("--------onUpdate Called--------"
+ oldVersion + "--->" + newVersion);
}
}

可以看到这个类继承了SQLiteOpenHelper并且重写了onCreate方法,当程序第一次启动时
系统就会调用onCreate方法来初始化底层数据

如果这个类的实例传入的数据的数据库版本号高于已有的版本号,
则系统会自动调用onUpgrade方法来更新数据库。

然后来看实例的程序,主界面如下:

<?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">
<EditText
android:id="@+id/word"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/detail"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/insert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/insert"/>
<EditText
android:id="@+id/key"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/search"/>
</LinearLayout>

主界面前两个输入框用来输入英文与相应的翻译,输入后点击insert按钮就将单词录入数据库

第三个输入框输入想要查询的英文,然后点击search按钮进行查询

MainActivity代码如下:

public class MainActivity extends AppCompatActivity {
MyDatabaseHelper dbHelper;
Button insert = null;
Button search = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//创建MyDatabaseHelper对象,指定数据库版本为1
dbHelper = new MyDatabaseHelper(this, "myDict.db3", 1);
insert = (Button) findViewById(R.id.insert);
search = (Button) findViewById(R.id.search);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String word = ((EditText)findViewById(R.id.word)).getText().toString();
String detail = ((EditText)findViewById(R.id.detail)).getText().toString();
//插入生词记录
insertData(dbHelper.getReadableDatabase(), word, detail);
Toast.makeText(MainActivity.this, "添加生词成功", Toast.LENGTH_SHORT).show();
}
});
search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//获取用户输入
String key = ((EditText)findViewById(R.id.key)).getText().toString();
//执行查询
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
"select * from dict where word like ? or detail like ?",
new String[] {"%" + key + "%", "%" + key + "%"});
//创建一个Bundle对象
Bundle data = new Bundle();
data.putSerializable("data", converCursorTolist(cursor));
//创建一个Intent
Intent intent = new Intent(MainActivity.this, ResultActivity.class);
intent.putExtras(data);
startActivity(intent);
}
});
}
protected ArrayList<Map<String, String>>
converCursorTolist(Cursor cursor){
ArrayList<Map<String, String>> result = new ArrayList<Map<String,String>>();
//遍历Cursor结果集
while (cursor.moveToNext())
{
Map<String, String> map = new HashMap<>();
map.put("word", cursor.getString(1));
map.put("detail", cursor.getString(2));
result .add(map);
}
return result;
}
private void insertData(SQLiteDatabase db, String word, String detail) {
//执行插入语句
db.execSQL("insert into dict values(null , ? , ?)"
, new String[]{word, detail });
} public void onDestroy(){
//退出程序时关闭数据库
super.onDestroy();
if (dbHelper != null){
dbHelper.close();
}
}
}

这个程序点击查询按钮时会跳转到ResultActivity,代码如下:

public class ResultActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
ListView listView = (ListView) findViewById(R.id.show);
Intent intent = getIntent();
//获取intent所携带的数据
Bundle data = intent.getExtras();
List<Map<String, String>> list = (List<Map<String, String>>)data.getSerializable("data");
//将List封装成SimpleAdapter
SimpleAdapter adapter = new SimpleAdapter(ResultActivity.this
, list,
R.layout.line, new String[]{ "word", "detail" }
, new int[] {R.id.word, R.id.detail});
//填充ListView
listView.setAdapter(adapter);
}
}

Android的SQlite的使用的更多相关文章

  1. Android之SQLite数据存储

    一.SQLite保存数据介绍 将数据库保存在数据库对于重复或者结构化数据(比如契约信息)而言是理想之选.SQL数据库的主要原则之一是架构:数据库如何组织正式声明.架构体现于用于创建数据库的SQL语句. ...

  2. android安卓Sqlite数据库实现用户登录注册

    看了很多别人写的安卓SQlite数据的操作代码,一点也不通俗易懂,我觉得我写的不错,而且安卓项目也用上了,所以在博客园里保存分享一下!建立一个类 并继承SQLiteOpenHelper public ...

  3. Android中SQLite数据库小计

    2016-03-16 Android数据库支持 本文节选并翻译<Enterprise Android - Programing Android Database Applications for ...

  4. android 对sqlite数据库的增删改查等各种操作

    转载:http://blog.csdn.net/vrix/article/details/6717090 package com.sqlite.main; import java.io.File; i ...

  5. Android学习---SQLite数据库的增删改查和事务(transaction)调用

    上一篇文章中介绍了手工拼写sql语句进行数据库的CRUD操作,本文将介绍调用sqlite内置的方法实现CRUD操作,其实质也是通过拼写sql语句. 首先,创建一个新的android项目: 其次,查看代 ...

  6. android数据库SQLite的设计模式

    Dao设计模式可能是使用最多的数据库的设计模式其基本思路是将数据库操作的代码 与设计代码分离以便于维护和升级.具体的实现方法是使用包,然后在设计代码中调 用数据库的操作代码,dao设计模式需要创建5个 ...

  7. Android使用SQLite数据库(2)

    打开SQLite数据库,首先要建立一个DatabaseHelper类的实例,然后,再获得数据库: DatabaseHelper mDBH; SQLiteDatabase db; mDBH = new ...

  8. 我的Android六章:Android中SQLite数据库操作

    今天学习的内容是Android中的SQLite数据库操作,在讲解这个内容之前小编在前面有一篇博客也是讲解了SQLite数据库的操作,而那篇博客的讲解是讲述了 如何在Window中通过DOM来操作数据库 ...

  9. Android和SQLite版本对应关系

    Android和SQLite版本对应关系 今天Xamarin群有人问到Android和SQLite版本如何对应,顺手查了一下,贴出来. SQLite 3.8.4.3: • 21-5.0-Lollipo ...

  10. Android中SQLite应用详解

    上次我向大家介绍了SQLite的基本信息和使用过程,相信朋友们对SQLite已经有所了解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite. 现在的主流移动设备像Android.i ...

随机推荐

  1. Android获取虚拟软键盘高度

    public static int getDpi(Context context) { int dpi = 0; WindowManager windowManager = (WindowManage ...

  2. day02 解释器安装及初识变量

    今日内容: 1.解释器的安装 2.添加到环境变量 3.pip初识 4.变量初识 5.PyCharm安装及激活 今日重点: 1.将python及pip添加到环境变量 在将python解释器安装到计算机后 ...

  3. Windows2016的 IIS中配置PHP7运行环境

    Windows2016的 IIS中配置PHP7运行环境 在Windows 的IIS(8.0)中搭建PHP运行环境: 一:安装IIS服务器 .进入控制面板>>程序和功能>>打开或 ...

  4. python套接字解决tcp粘包问题

    python套接字解决tcp粘包问题 目录 什么是粘包 演示粘包现象 解决粘包 实际应用 什么是粘包 首先只有tcp有粘包现象,udp没有粘包 socket收发消息的原理 发送端可以是一K一K地发送数 ...

  5. Vuex数据可视化

    参考:https://gitee.com/hjm100/codes/46towe9v28a1bxfqhc7kl34 Vuex虽然能存储数据,但是一刷新就没有了,如果要实现数据持久化,就需要用vuex- ...

  6. notepad++最详情汇总

    1.安装nodepad++ 2.sitting-转换中文语言 3.view-设置自动换行 4.安装格式化插件----https://github.com/bruderstein/nppPluginMa ...

  7. mysql拼接字符串

    CONCAT(str1,str2,...) 如:在每一列meeting_persons的现有内容之上,增加15112319字符串 UPDATE wos_hrs.meeting_logs SET mee ...

  8. 14.并发与异步 - 3.C#5.0的异步函数 -《果壳中的c#》

    14.5.2 编写异步函数 private static readonly Stopwatch Watch = new Stopwatch(); static void Main(string[] a ...

  9. Spring Boot+CXF搭建WebService(转)

    概述 最近项目用到在Spring boot下搭建WebService服务,对Java语言下的WebService了解甚少,而今抽个时间查阅资料整理下Spring Boot结合CXF打架WebServi ...

  10. Codeforces 375B Maximum Submatrix 2 (DP)

    <题目链接> 题目大意:给出一个01矩阵,行与行之间可以互换位置,问能够得到最大的全1矩阵的面积. #include <bits/stdc++.h> using namespa ...