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. 在deepin 15.5中安装vs code并配置c/c++环境

    原文地址:https://blog.csdn.net/DefetC/article/details/79946100 参考了以下几篇文章: https://www.zhihu.com/question ...

  2. LNMP环境搭建:Nginx安装、测试与域名配置

    Nginx作为一款优秀的Web Server软件同时也是一款优秀的负载均衡或前端反向代理.缓存服务软件 2.编译安装Nginx (1)安装Nginx依赖函数库pcre pcre为“perl兼容正则表达 ...

  3. JAVA 数组元素的反转

    package Code411;/*数组元素的反转本来[1,2,3,4]反转后[4,3,2,1]1.对称位置的元素交换2.对称位子需要两个索引3.int temp =a:a=b;b=temp;4.什么 ...

  4. Django—模型

    索引 1.定义模型类 2.模型类 3.字段查询 4.查询集 5.模型类关系 6.模型类扩展 ORM简介 ORM,全拼Object-Relation Mapping,中文意为对象-关系映射,是随着面向对 ...

  5. 网络流24题——试题库问题 luogu 2763

    题目描述看:这里 这是我们遇到的第一个要求输出方案的问题 考虑建图然后用最大流思想: 首先由源点向每一道试题连边,容量为1 然后由每一种试题类型向汇点连边,容量为需求量 最后由每一道试题向可能属于的试 ...

  6. 2017-2018-2 20155309南皓芯 Exp4 恶意代码分析

    实验后回答问题 (1)如果在工作中怀疑一台主机上有恶意代码,但只是猜想,所有想监控下系统一天天的到底在干些什么.请设计下你想监控的操作有哪些,用什么方法来监控. 答:我会使用sysmon工具来进行监控 ...

  7. Django web框架

    urls的配置 views视图函数 tempalte模板 settings的配置 Django目录结构分析 Django主线 Django-model基础 Django-model聚合查询与分组查询 ...

  8. 解决 RecyclerView 在Android Studio已经导入情况下还无法实例引用问题

    系统:Windows 10 IDE::android studio 1. 问题:RecyclerView 在Android Studio已经导入情况下还无法实例引用问题 由于RecyclerView是 ...

  9. tensorflow变量-【老鱼学tensorflow】

    在程序中定义变量很简单,只要定义一个变量名就可以,但是tensorflow有点类似在另外一个世界,因此需要通过当前的世界中跟tensorlfow的世界中进行通讯,来告诉tensorflow的世界中定义 ...

  10. 单元测试如何覆盖internal的方法

    在类的设计中经常会有类或者方法要设置成private或者internal等方式,在使用中这么做无可厚非,但是对单元测试的影响也颇大 对于private方法,那只有做一个副本然后改成internal或p ...