1、在 Android 中使用 SQLite ContentProviderAndroid- 数据库支持(SQLite), 内容提供器(ContentProvider)系出名门Android(9) - 数据库支持(SQLite), 内容提供器(ContentProvider)作者:webabcd介绍在 Android 中使用 SQLite, ContentProvider 数据库支持(SQLite) - Android 开发平台提供了操作 SQLite 数据库的相关 API 内容提供器(ContentProvider) - 当数据需要在应用程序之间共享时,可以在某程序中使用 ContentProv
2、ider 定义 URI, 以使其它应用程序可以通过此 URI 访问指定的数据1、SQLite 的 DemoDatabaseHelper.java代码package com.webabcd.SQLite;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.database.sqlite.SQLiteDatabase.CursorFactory;/ 数据库操作的 Helpe
3、r 类public class DatabaseHelper extends SQLiteOpenHelper DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version) super(context, name, cursorFactory, version);Overridepublic void onCreate(SQLiteDatabase db) / TODO 创建数据库后,对数据库的操作Overridepublic void onUpgrade(SQLiteDatabas
4、e db, int oldVersion, int newVersion) / TODO 更改数据库版本的操作Overridepublic void onOpen(SQLiteDatabase db) super.onOpen(db);/ TODO 每次成功打开数据库后首先被执行Main.java代码package com.webabcd.SQLite;import java.util.Random;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;im
5、port android.database.SQLException;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;public class Main extends Activity private DatabaseHelper dbHelper;private static final String DATABASE_NAME
6、= db.db;private static final int DATABASE_VERSION = 1;private static final String TABLE_NAME = employee;TextView txtMsg;/* Called when the activity is first created. */Overridepublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.main);dbHelper =
7、new DatabaseHelper(this, DATABASE_NAME, null,DATABASE_VERSION);txtMsg = (TextView) this.findViewById(R.id.txtMsg);Button btn1 = (Button) this.findViewById(R.id.btn1);btn1.setText(创建表);btn1.setOnClickListener(new Button.OnClickListener() public void onClick(View v) CreateTable(););Button btn2 = (Butt
8、on) this.findViewById(R.id.btn2);btn2.setText(插入 3 条记录);btn2.setOnClickListener(new Button.OnClickListener() public void onClick(View v) insertItem(););Button btn3 = (Button) this.findViewById(R.id.btn3);btn3.setText(删除全部记录);btn3.setOnClickListener(new Button.OnClickListener() public void onClick(Vi
9、ew v) deleteItem(););Button btn4 = (Button) this.findViewById(R.id.btn4);btn4.setText(更新指定数据);btn4.setOnClickListener(new Button.OnClickListener() public void onClick(View v) updateItem(););Button btn5 = (Button) this.findViewById(R.id.btn5);btn5.setText(显示全部数据);btn5.setOnClickListener(new Button.On
10、ClickListener() public void onClick(View v) showItems(););Button btn6 = (Button) this.findViewById(R.id.btn6);btn6.setText(删除表);btn6.setOnClickListener(new Button.OnClickListener() public void onClick(View v) dropTable(););/ 创建数据表private void CreateTable() SQLiteDatabase db = dbHelper.getWritableDat
11、abase();String sql = CREATE TABLE IF NOT EXISTS + TABLE_NAME+ (ID INTEGER PRIMARY KEY, Name VARCHAR, Age INTEGER);try db._execSQL(sql);txtMsg.append(数据表成功创建n); catch (SQLException ex) txtMsg.append(数据表创建错误n + ex.toString() + n);/ 插入数据private void insertItem() SQLiteDatabase db = dbHelper.getWritable
12、Database();try Random random = new Random();for (int i = 0; i 3; i+) String sql = insert into + TABLE_NAME+ (name, age) values (name + String.valueOf(i)+ , + random.nextInt() + );/ _execSQL() - 执行指定的 sqldb._execSQL(sql);txtMsg.append(成功插入 3 条数据n); catch (SQLException ex) txtMsg.append(插入数据失败n + ex.t
13、oString() + n);/ 删除数据private void deleteItem() try SQLiteDatabase db = dbHelper.getWritableDatabase();db.delete(TABLE_NAME, id 999999, null);txtMsg.append(成功删除数据n); catch (SQLException e) txtMsg.append(删除数据失败n);/ 更新数据private void updateItem() SQLiteDatabase db = dbHelper.getWritableDatabase();try Co
14、ntentValues values = new ContentValues();values.put(name, 批量更新后的名字);db.update(TABLE_NAME, values, id?, new String 3 );txtMsg.append(成功更新数据n); catch (SQLException e) txtMsg.append(更新数据失败n);/ 查询数据private void showItems() SQLiteDatabase db = dbHelper.getReadableDatabase();try String column = id, name,
15、age ;Cursor cursor = db.query(TABLE_NAME, column, null, null, null,null, null);Integer num = cursor.getCount();txtMsg.append(共 + Integer.toString(num) + 条记录n);cursor.moveToFirst();while (cursor.getPosition() != cursor.getCount() txtMsg.append(Integer.toString(cursor.getPosition() + ,+ String.valueOf
16、(cursor.getString(0) + ,+ cursor.getString(1) + ,+ String.valueOf(cursor.getString(2) + n);cursor.moveToNext(); catch (SQLException ex) txtMsg.append(读取数据失败n + ex.toString() + n);/ 删除数据表private void dropTable() SQLiteDatabase db = dbHelper.getWritableDatabase();String sql = DROP TABLE IF EXISTS + TA
17、BLE_NAME;try db._execSQL(sql);txtMsg.append(数据表删除成功n); catch (SQLException ex) txtMsg.append(数据表删除错误n + ex.toString() + n);2、ContentProvider 的 DemoMyUser.java代码package com.webabcd.contentprovider;import .Uri;import android.provider.BaseColumns;/ 自定义 ContentProvider 所需的实体类public class MyUser / 必须要有 _
18、id 字段。本例中 BaseColumn 类中已经包含了 _id 字段public static final class User implements BaseColumns / 定义 CONTENT_URIpublic static final Uri CONTENT_URI = Uri.parse(content:/com.webabcd.MyContentProvider);/ 表数据列public static final String USER_NAME = USER_NAME;MyContentProvider.java代码package com.webabcd.contentp
19、rovider;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import org.apache.http.util.EncodingUtils;import android.content.ContentProvider;import android.content.ContentUris;import android.content.ContentValues;import android.database.Cursor;import android.database.M
20、atrixCursor;import .Uri;/ 继承 ContentProvider 以实现自定义的 ContentProvider(基于文件的信息存储)public class MyContentProvider extends ContentProvider private File file;private FileOutputStream out;private FileInputStream in;/ ContentProvider 的删除数据接口Overridepublic int delete(Uri uri, String selection, String selecti
21、onArgs) / TODO Auto-generated method stubreturn 0;Overridepublic String getType(Uri uri) / TODO Auto-generated method stubreturn null;/ ContentProvider 的插入数据接口 Overridepublic Uri insert(Uri uri, ContentValues values) try out = new FileOutputStream(file);out.write(values.getAsString(MyUser.User.USER_
22、NAME).getBytes();out.close();int rowId = 0;Uri rowUri = ContentUris.appendId(MyUser.User.CONTENT_URI.buildUpon(), rowId).build();getContext().getContentResolver().notifyChange(rowUri, null);return rowUri; catch (Exception e) return null;/ 创建用于保存信息的文件Overridepublic boolean onCreate() try / 每个包中应用程序的私
23、有目录为:/data/data/包名/ SD 卡目录为:/sdcardfile = new File(/data/data/com.webabcd.contentprovider/,demo.txt);if (!file.exists()file.createNewFile();return true; catch (Exception ex) return false;/ ContentProvider 的查询数据接口Overridepublic Cursor query(Uri uri, String projection, String selection,String selectio
24、nArgs, String sortOrder) String content;try in = new FileInputStream(file);int length = (int) file.length();byte buffer = new bytelength;in.read(buffer, 0, length);content = EncodingUtils.getString(buffer, UTF-8);in.close();String columns = new String MyUser.User._ID, MyUser.User.USER_NAME ;MatrixCu
25、rsor cur = new MatrixCursor(columns);String values = new String 0, content ;cur.moveToFirst();cur.addRow(values);return cur; catch (Exception e) return null;/ ContentProvider 的更新数据接口Overridepublic int update(Uri uri, ContentValues values, String selection,String selectionArgs) / TODO Auto-generated
26、method stubreturn 0;Main.java代码package com.webabcd.contentprovider;import java.util.Random;import android.app.Activity;import android.content.ContentUris;import android.content.ContentValues;import android.database.Cursor;import .Uri;import android.os.Bundle;import android.provider.Contacts;import a
27、ndroid.provider.Contacts.People;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast;/* 几个常用的系统内置的 ContentProvider 如下: * content:/media/internal/images 这个URI将返回设备上存储的所有图片* content:/contacts/people/ 这个URI将返回设备上的所有联系人信息* content:/contacts/people/45
28、这个URI返回单个结果(联系人信息中ID为45的联系人记录)*/public class Main extends Activity /* Called when the activity is first created. */Overridepublic void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.main);Button btn1 = (Button) this.findViewById(R.id.btn1);btn1.setText
29、(新增联系人记录);btn1.setOnClickListener(new Button.OnClickListener() public void onClick(View v) Random random = new Random();insertRecords(name + String.valueOf(random.nextInt(), String.valueOf(random.nextInt(););Button btn2 = (Button) this.findViewById(R.id.btn2);btn2.setText(查看联系人记录);btn2.setOnClickListener(new Button.OnClickListener() public void onClick(View v) displayRecords(););
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1