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. vue之vuex学习

    知识点一:vuex是状态管理器(单向数据流) 每个Vuex应用程序的核心是商店.“商店”基本上是一个容纳您的应用程序状态的容器.有两件事使Vuex商店与普通的全局对象不同: Vuex商店是被动的.当V ...

  2. 【easy】226. Invert Binary Tree 反转二叉树

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  3. 【剑指offer】【python】面试题2~5

    使用python实现<剑指offer>面试题ヾ(◍°∇°◍)ノ゙,以此记录. 2_实现Singleton模式 题目:实现单例模式 单例模式,是一种常用的软件设计模式.在它的核心结构中只包含 ...

  4. jqGrid合并单元格

    两个参数 /**合并单元格:合并指定 gridName表格的NoName 列,合并的标准是参考CellName+CellNameTwo列内单元格的值. * gridName :表格名称 * NoNam ...

  5. 三目算法、if/else,switch/case运用

    //输入学生的成绩,判断考试是否及格,及格6大于等于0 //第一种写法:三目运算 大多用于单独判断是否满足某个条件 import java.util.Scanner; public class Hel ...

  6. iOS -- Effective Objective-C 阅读笔记 (9)

    // 将类的实现方法代码反三到便于管理的数个分类之中.        // 类中经常容易填满各种方法, 而这些方法的代码则全部堆在一个巨大的实现文件中, 有时这么做事不合理的,因为即使通过重构把这个类 ...

  7. Java+maven+httpcomponents封装post/get请求

    httpcore4.4.10, httpclient4.5.6 package com.test.http; import com.alibaba.fastjson.JSONArray; import ...

  8. Three teachers who make differences in my life

    人生路漫漫,从小到大,经历过九年义务教育的我们也受到过很多老师的熏陶,而已经进入大学的我也会回想起那些给我带来别样意义的老师们. 亲爱的老李-老李是我初中的班主任,也是我的历史老师.依稀记得上他的课会 ...

  9. Vue中父子组件通讯——组件todolist

    一.todolist功能开发 <div id="root"> <div> <input type="text" v-model=& ...

  10. IDEA上创建 Maven SpringBoot + zookeeper +dubbo 实例

    概述 首先声明,本文是学习总结类型的博客内容,如有雷同纯属学习.本位主要结合zookeeper和dubbo做个简单实例.目前来说,一般网站架构随着业务的发展,逻辑越来越复杂,数据量越来越大,交互越来越 ...