位置: 编程技术 - 正文
推荐整理分享使用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数据库
常有人问:如何删除自己创建的数据库?
在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的实现细节)(如何开发一个新的向量库)
友情链接: 武汉网站建设