位置: 编程技术 - 正文

使用SQLite本地数据库

编辑:rootadmin

推荐整理分享使用SQLite本地数据库,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

在Android平台上,集成了一个嵌入式关系型数据库—SQLite。以SQLite是一款轻型数据库:SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型只有五种,但实际上sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型,只不过在运算或保存时会转成对应的五种数据类型。

  SQLite可以解析大部分标准SQL语句。

一、设计界面

  1、布局文件

  打开res/layout/activity_main.xml文件。  输入以下代码:

[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#EFEFEF"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/prompt" android:textColor="@drawable/black" /> <EditText android:id="@&#;id/editbook" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@drawable/black" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="作者:" android:textColor="@drawable/black" /> <EditText android:id="@&#;id/editauthor" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@drawable/black" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="出版社:" android:textColor="@drawable/black" /> <EditText android:id="@&#;id/editpublisher" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="@drawable/black" /> <ListView android:id="@&#;id/listview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/black" /> </LinearLayout>

 2、自定义列表文件

  打开res/layout/list.xml文件。  输入以下代码:

[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent"> <CheckedTextView android:id="@&#;id/textbookname" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@&#;id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/list_driver" /> <CheckedTextView android:id="@&#;id/textauthor" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ImageView android:id="@&#;id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/list_driver" /> <CheckedTextView android:id="@&#;id/textpublisher" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>

  3、颜色文件

  打开res/values/color.xml文件。  输入以下代码:

[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <resources> <drawable name="black">#</drawable> <drawable name="white">#FFFFFFFF</drawable> <drawable name="gray">#EFEFEF</drawable> </resources>

  4、字符串文件

  打开res/values/string.xml文件。  输入以下代码:

[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">SQLite</string> <string name="prompt">书名:(请使用菜单:完成新增、修改、查询、刪除记录)</string> <string name="addrec">新增</string> <string name="editrec">修改</string> <string name="queryrec">查询</string> <string name="delrec">刪除</string> </resources>

二、程序文件

  1、SQLiteHelper.java文件

  打开“src/com.genwoxue.sqlite/SQLiteHelper.java”文件。  然后输入以下代码:

[java] view plaincopypackage com.genwoxue.sqlite; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class SQLiteHelper extends SQLiteOpenHelper { private final static String DATABASE_NAME = "Library"; private final static int DATABASE_VERSION = 1; private final static String TABLE_NAME = "Book"; //构造函数,创建数据库 public SQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } //建表 public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " &#; TABLE_NAME &#; "(_id INTEGER PRIMARY KEY," &#; " BookName VARCHAR() NOT NULL," &#; " Author VARCHAR()," &#; " Publisher VARCHAR())"; db.execSQL(sql); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " &#; TABLE_NAME; db.execSQL(sql); onCreate(db); } //获取游标 public Cursor select() { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null); return cursor; } //插入一条记录 public long insert(String bookName,String author,String publisher ) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put("BookName", bookName); cv.put("Author", author); cv.put("Publisher", publisher); long row = db.insert(TABLE_NAME, null, cv); return row; } //根据条件查询 public Cursor query(String[] args) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM "&#;TABLE_NAME&#;" WHERE BookName LIKE ?", args); return cursor; } //删除记录 public void delete(int id) { SQLiteDatabase db = this.getWritableDatabase(); String where ="_id = ?"; String[] whereValue = { Integer.toString(id) }; db.delete(TABLE_NAME, where, whereValue); } //更新记录 public void update(int id, String bookName,String author,String publisher) { SQLiteDatabase db = this.getWritableDatabase(); String where = "_id = ?"; String[] whereValue = { Integer.toString(id) }; ContentValues cv = new ContentValues(); cv.put("BookName", bookName); cv.put("Author", author); cv.put("Publisher", publisher); db.update(TABLE_NAME, cv, where, whereValue); } }

  2、MainActivity.java文件

  打开“src/com.genwoxue.sqlite/MainActivity.java”文件。  然后输入以下代码:

[java] view plaincopypackage com.genwoxue.sqlite; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MainActivity extends Activity { private SQLiteHelper helper; private Cursor cursor; private ListView lvBook; private EditText editBook; private EditText editAuthor; private EditText editPublisher; private int id=0; protected final static int MENU_ADD = Menu.FIRST; protected final static int MENU_EDIT = Menu.FIRST &#; 1; protected final static int MENU_QUERY = Menu.FIRST &#; 2; protected final static int MENU_DELETE = Menu.FIRST &#; 3; //执行菜单选项 public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_ADD: this.addRec(); break; case MENU_EDIT: this.editRec(); break; case MENU_QUERY: this.queryRec(); break; case MENU_DELETE: this.deleteRec(); break; } return true; } //初始化菜单 public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(Menu.NONE, MENU_ADD, 0, R.string.addrec).setIcon(android.R.drawable.ic_menu_add); menu.add(Menu.NONE, MENU_EDIT, 0, R.string.editrec).setIcon(android.R.drawable.ic_menu_edit); menu.add(Menu.NONE,MENU_QUERY,0,R.string.queryrec).setIcon(android.R.drawable.ic_menu_search); menu.add(Menu.NONE, MENU_DELETE, 0, R.string.delrec).setIcon(android.R.drawable.ic_menu_delete); return true; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lvBook = (ListView) this.findViewById(R.id.listview); editBook = (EditText) this.findViewById(R.id.editbook); editAuthor=(EditText) this.findViewById(R.id.editauthor); editPublisher=(EditText) this.findViewById(R.id.editpublisher); //表中内容填充到自定义ListView helper = new SQLiteHelper(this); cursor = helper.select(); SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.list, cursor, new String[] {"BookName","Author","Publisher"}, new int[] { R.id.textbookname,R.id.textauthor,R.id.textpublisher} ); lvBook.setAdapter(adapter); // lvBook设置OnItemClickListener监听事件 lvBook.setOnItemClickListener(new AdapterView.OnItemClickListener(){ public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){ cursor.moveToPosition(arg2); // 将cursor移到所点击的&#; id = cursor.getInt(0); // 取得字段_id的&#; editBook.setText(cursor.getString(1)); // 取得字段Rec_text的&#; editAuthor.setText(cursor.getString(2)); editPublisher.setText(cursor.getString(3)); } }); } //添加记录 private void addRec() { if (editBook.getText().toString().equals("")) return; helper.insert(editBook.getText().toString(),editAuthor.getText().toString(),editPublisher.getText().toString()); //重新加载数据 cursor.requery(); lvBook.invalidateViews(); editBook.setText(""); editAuthor.setText(""); editPublisher.setText(""); } // 修改记录 private void editRec() { if (editBook.getText().toString().equals("")) return; helper.update(id, editBook.getText().toString(),editAuthor.getText().toString(),editPublisher.getText().toString()); //重新加载数据 cursor.requery(); lvBook.invalidateViews(); editBook.setText(""); editAuthor.setText(""); editPublisher.setText(""); } //根据书名查询 private void queryRec() { String et=editBook.getText().toString(); String args[]=new String[]{"%"&#;et&#;"%"}; cursor=helper.query(args); SimpleCursorAdapter adapter = new SimpleCursorAdapter( this, R.layout.list, cursor, new String[] {"BookName","Author","Publisher"}, new int[] { R.id.textbookname,R.id.textauthor,R.id.textpublisher} ); lvBook.setAdapter(adapter); } //删除记录 private void deleteRec() { helper.delete(id); cursor.requery(); lvBook.invalidateViews(); editBook.setText(""); } }

三、配置文件

  打开“AndroidManifest.xml”文件。  然后输入以下代码:

[html] view plaincopy<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android=" package="com.genwoxue.sqlite" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.genwoxue.sqlite.MainActivity" android:label="@string/app_name" <span style="color:#ff;"><strong>android:theme="@android:style/Theme"</strong> </span>> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

  注意:在Android4.0中,如果想显示2.3版本中样式的菜单,需要在配置文件中填加以上红色代码。

使用SQLite本地数据库

四、运行结果

   

  说明:输入内容,单击“新增”菜单,则添加一条记录;也可以根据书名查询相应书籍;也可以选中某条记录,然后单击“修改”或“删除”菜单。

  

附:

(一)如何删除Sqlite数据库

  常有人问:如何删除自己创建的数据库?

  在Activity中,提供有现成的方法:public boolean deleteDatabase (String name)

(二)SimpleCursorAdapter简要说明

  描述:

  SimpleCurosrAdapter 是一个将 Cursor 中的 columns 与在 XML 文件中定义的 TextViews 或 ImageViews 进行匹配的简易 adapter。你可以指定选择 Cursor 中的哪些 columns、用哪些 views 来显示这些 columns 、以及指定定义这些 views 的 xml 文件。

也就是说,SimpleCursorAdapter 允许绑定一个 Cursor 的 columns 到 ListView 上,并使用自定义的 layout 显示 List中的每个项目。

可以使用 SimpleCursorAdapter 作为中间桥梁,将从 sqlite 数据库中查询出来的数据直接显示到 ListView 中。  原型:

  public SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {

     super(context, layout, c);      mTo = to;      mOriginalFrom = from;      findColumns(from);   }

  参数:

  Context context, 这个与 SimpleListItemFactory 相关的 ListView 所处运行上下文(context)。也就是这个 ListView 所在的 Activity。

  int layout, 显示 list item 的 布局文件。这个 layout 文件中至少要包含在 "to" 参数中命名的 views。

  Cursor c,数据库的光标( Cursor )。如果 cursor 无效,则该参数可以为 null

  String[] from, 指定 column 中的哪些列的数据将绑定(显示)到 UI 中。如果 cursor 无效, 则该参数可为 null。

  int[] to, 指定用于显示 "from" 参数指定的数据列表的 views。 这些 views 必须都是 TextViews。 "from" 参数的前 N 个&#;(valus)和 "to" 参数的前 N 个 views 是一一对应的关系。如果 cursor 无效,则该参数可为 null。

如何开发一个新闻订阅APP之Android篇(二、从“逛”页面谈谈多种格式listview的实现细节) 上一篇文章如何开发一个新闻订阅APP之Android篇(一、实现仿微信主界面效果)介绍了布板主界面的实现,接下来,我想和大家分享一下ListView的一些使

Android使用局和数据实现天气项目-android学习之旅(十二) 1.首先注册聚合数据账号,下载相应的sdk2.导入jar包和so文件配置Application,初始化sdkapplication//自己新建的application类android:name="com.juhe.weather.WeatherApplicatio

WebView 布局设置fill_parent carch android4.4.2android5.0在fragment加载webview布局设置为android:layout_width=fill_parentandroid:layout_height=wrap_contentwebview加载H5,设置WebSettingswebSettings=webView.getSettings();webS

标签: 使用SQLite本地数据库

本文链接地址:https://www.jiuchutong.com/biancheng/385249.html 转载请保留说明!

上一篇:ubuntu下创建手机可用的热点wifi(ubuntu系统的手机)

下一篇:如何开发一个新闻订阅APP之Android篇(二、从“逛”页面谈谈多种格式listview的实现细节)(如何开发一个新的向量库)

  • 启用新账簿时,应填写
  • 北京增值税认证平台电话
  • 对方给我公司开的红字发票如何查询
  • 公司欠款利息收入需要交增值税吗?
  • 事务所纳税
  • 软件行业个人所得税
  • 支付给个人的佣金怎么做账务处理
  • 记载资金的账簿要交印花税吗
  • 车船税没有发票可以税前扣除吗
  • 支付给对方的押金
  • 民间非营利性组织
  • 工会筹备金税率
  • 交易性金融资产的交易费用计入哪里
  • 视同销售的消费税计入成本吗?
  • 办公室购置空调的词语
  • 固定资产处理申请
  • 增值税普通发票几个点
  • 企业盈利所得税交多少
  • 建筑业简易计税进项税可以抵扣吗
  • 1697508131
  • 小规模核定销售额是什么意思
  • 库存商品结转会计分录
  • 酒店开业请吃饭敬酒怎么说
  • 苹果电脑快速启动键是哪个
  • 我国现行的关税税率种类及适用
  • 野生动物保护区有哪些
  • cpqinet.exe是什么进程 安全吗 cpqinet进程安全性评估
  • php curl cookie
  • 待提出票据交换及转汇款怎么做账
  • 增值税一般纳税人登记管理办法
  • 手把手教你在瑞典停车
  • bert模型能做什么
  • x-s和web_session
  • 如何在idea中创建xml
  • 微信小程序在哪里找?
  • 如何修改php.ini
  • 增值税发票打印出格了能用吗
  • 企业能否自行填开发票入账
  • 26个字母!
  • 股东分红后股票会涨吗
  • php判断https
  • java基础介绍
  • 长期股权投资成本法
  • 金融资产减值包括
  • 小规模纳税人都报什么税
  • 委托加工物资的消费税
  • 应收账款周转速度快表明
  • 总账与总账之间的核对
  • 当事人对付款时间没有约定或者约定不明的
  • 购车税费怎样计算2023
  • 异地预缴怎么填写申报表
  • 房产税税率采用比例税率按照房产余值计征的年税率为
  • 产品检测费怎么入账
  • 防伪公司应该选用什么目标市场策略
  • 库存现金的使用限额
  • 公司基本户可以变更吗
  • 企业各种盘盈和盘亏分录
  • 贸易公司的经营模式
  • 日记账公式怎么设置
  • mysql5.7主从配置
  • 关于国际学校
  • mysql连接数 是针对db还是服务器
  • win10预览版绿屏重启解决
  • 平板电脑中的电池工作时是将什么能转化成了电能
  • 怎样设置Win XP下安装打印机驱动程序
  • win8怎么改文件格式
  • win8正版系统自带
  • linux系统的安装和常用命令
  • 搭建android开发环境需要用到哪些工具
  • mvp设计方案
  • 基于python的游戏
  • jquerychange事件
  • 安卓框架是什么怎么用
  • javascript如何学
  • 一般纳税人收到普通发票怎么做分录
  • 重庆车辆检测费多少钱
  • 深圳企业公积金更改代扣银行
  • 税务登记证用来干嘛
  • 海关进口增值税怎么认证抵扣
  • 四川投诉电话查询
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设