Create contentprovider and use contentresolver

Source: Internet
Author: User

1. Create contentprovider

 

Define (content required for client calls) Interface

package com.gogler.content;import android.net.Uri;import android.provider.BaseColumns;public class Users {public static final String AUTHORITY = "com.gogler.content";public static final class User implements BaseColumns{public static final Uri CONTENT_URI  = Uri.parse("content://com.gogler.content");       public static final String  USER_NAME  = "USER_NAME"; }}

 

Implement content providers

 

Package COM. gogler. content; import android. content. contentprovider; import android. content. contenturis; import android. content. contentvalues; import android. content. context; import android. database. cursor; import android. database. sqlexception; import android. database. SQLite. sqlitedatabase; import android. database. SQLite. sqliteopenhelper; import android. database. SQLite. sqlitequerybuilder; import android.net. u Ri; public class sumarycontentprovider extends contentprovider {private sqlitedatabase sqldb; private databasehelper dbhelper; Private Static final string database_name = "users. DB "; Private Static final int database_version = 1; Private Static final string table_name =" user "; Private Static final string tag =" sumarycontentprovider "; Private Static class databasehelper extends sqliteopenhelper {databa Sehelper (context) {super (context, database_name, null, database_version) ;}@ override public void oncreate (sqlitedatabase dB) {// create a table db.exe csql ("create table" + table_name + "(_ id integer primary key autoincrement," + "user_name text );");} @ override public void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {db.exe csql ("Drop table if exists" + table_name); oncr Eate (db) ;}@ overridepublic int Delete (URI Uri, string S, string [] as) {return 0 ;}@ overridepublic string GetType (URI) {return NULL ;}@ overridepublic URI insert (URI Uri, contentvalues) {sqldb = dbhelper. getwritabledatabase (); long rowid = sqldb. insert (table_name, "", contentvalues); If (rowid> 0) {URI rowuri = contenturis. appendid (users. user. content_uri.buildupon (), rowid ). bui LD (); getcontext (). getcontentresolver (). policychange (rowuri, null); Return rowuri;} Throw new sqlexception ("failed to insert row into" + URI);} @ overridepublic Boolean oncreate () {dbhelper = new databasehelper (getcontext (); Return (dbhelper = NULL )? False: true;} @ overridepublic cursor query (URI Uri, string [] projection, string selection, string [] selectionargs, string sortorder) {sqlitequerybuilder QB = new sqlitequerybuilder (); sqlitedatabase DB = dbhelper. getreadabledatabase (); QB. settables (table_name); cursor c = QB. query (dB, projection, selection, null, sortorder); C. setnotificationuri (getcontext (). getcontentresolver (), Uri); Return C ;}@ overridepublic int Update (URI Uri, contentvalues, string S, string [] as) {return 0 ;}}

 

2. Use the content provider contentresolver (client)

 

package com.gogler.content;import android.app.Activity;import android.content.ContentValues;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.widget.Toast;public class ContentSumaryActivity extends Activity {@Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        for(int i =1; i<=10; i++){        insertRecord("User"+i);        }        displayRecords();    }       private void insertRecord(String userName) {        ContentValues values = new ContentValues();        values.put(Users.User.USER_NAME, userName);        getContentResolver().insert(Users.User.CONTENT_URI, values);    }   private void displayRecords() {        String columns[] = new String[] { Users.User._ID, Users.User.USER_NAME };        Uri myUri = Users.User.CONTENT_URI;        Cursor cur = managedQuery(myUri, columns,null, null, null );        if (cur.moveToFirst()) {            String id = null;            String userName = null;            do {                id = cur.getString(cur.getColumnIndex(Users.User._ID));                userName = cur.getString(cur.getColumnIndex(Users.User.USER_NAME));                Toast.makeText(this, id + " " + userName, Toast.LENGTH_LONG).show();           } while (cur.moveToNext());       }    }}

 

3. Reference

Android basics: Android content provider

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.