您的位置:首页 > 移动开发 > Android开发

android developer tiny share-20170505

2017-05-05 16:17 99 查看
今天继续讲android的ContentProvider,讲设计自己的ContentProvider,需要继承ContentProvider类,实现6个方法,分别是query()、insert()、update()、delete()、getType()、onCreate()。前5个方法之前已经讲过了,今天讲最后一个方法,onCreate()。

以下是android developer官网的讲解:

实现 onCreate() 方法

Android 系统会在启动提供程序时调用 onCreate()。您只应在此方法中执行运行快速的初始化任务,并将数据库创建和数据加载推迟到提供程序实际收到数据请求时进行。 如果您在 onCreate() 中执行长时间的任务,则会减慢提供程序的启动速度, 进而减慢提供程序对其他应用的响应速度。

例如,如果您使用 SQLite 数据库,可以在 ContentProvider.onCreate() 中创建一个新的 SQLiteOpenHelper 对象,然后在首次打开数据库时创建 SQL 表。 为简化这一过程,在您首次调用 getWritableDatabase() 时,它会自动调用 SQLiteOpenHelper.onCreate() 方法。

以下两个代码段展示了 ContentProvider.onCreate() 与 SQLiteOpenHelper.onCreate() 之间的交互。第一个代码段是 ContentProvider.onCreate() 的实现:

public class ExampleProvider extends ContentProvider

/*
* Defines a handle to the database helper object. The MainDatabaseHelper class is defined
* in a following snippet.
*/
private MainDatabaseHelper mOpenHelper;

// Defines the database name
private static final String DBNAME = "mydb";

// Holds the database object
private SQLiteDatabase db;

public boolean onCreate() {

/*
* Creates a new helper object. This method always returns quickly.
* Notice that the database itself isn't created or opened
* until SQLiteOpenHelper.getWritableDatabase is called
*/
mOpenHelper = new MainDatabaseHelper(
getContext(), // the application context
DBNAME, // the name of the database)
null, // uses the default SQLite cursor
1 // the version number
);

return true;
}

...

// Implements the provider's insert method
public Cursor insert(Uri uri, ContentValues values) {
// Insert code here to determine which table to open, handle error-checking, and so forth

...

/*
* Gets a writeable database. This will trigger its creation if it doesn't already exist.
*
*/
db = mOpenHelper.getWritableDatabase();
}
}

下一个代码段是 SQLiteOpenHelper.onCreate() 的实现,其中包括一个帮助程序类:
...
// A string that defines the SQL statement for creating a table
private static final String SQL_CREATE_MAIN = "CREATE TABLE " +
"main " + // Table's name
"(" + // The columns in the table
" _ID INTEGER PRIMARY KEY, " +
" WORD TEXT"
" FREQUENCY INTEGER " +
" LOCALE TEXT )";
...
/**
* Helper class that actually creates and manages the provider's underlying data repository.
*/
protected static final class MainDatabaseHelper extends SQLiteOpenHelper {

/*
* Instantiates an open helper for the provider's SQLite data repository
* Do not do database creation and upgrade here.
*/
MainDatabaseHelper(Context context) {
super(context, DBNAME, null, 1);
}

/*
* Creates the data repository. This is called when the provider attempts to open the
* repository and SQLite reports that it doesn't exist.
*/
public void onCreate(SQLiteDatabase db) {

// Creates the main table
db.execSQL(SQL_CREATE_MAIN);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息