コンテントプロバイダ演習コード

NotesContentProvider.java

package com.example.contentprovider;

 

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.UriMatcher;

import android.database.Cursor;

import android.net.Uri;

import android.provider.BaseColumns;

import android.text.TextUtils;

import android.util.Log;

 

import com.android.demo.notepad3.NotesDbAdapter;

 

public class NotesContentProvider extends ContentProvider{

    public static final String PROVIDER_NAME="com.example.contentprovider.notes";

    private static final UriMatcher uriMatcher;

    private NotesDbAdapter notesDbAdapter;

 

    public static final class Notes implements BaseColumns {// _ID _COUNTが定義されている。

        public static final Uri CONTENT_URI

         =Uri.parse("content://" + PROVIDER_NAME + "/notes");//// URI for access the Content Provider

        public static final String DATABASE_TABLE = "notes";

        public static final String DEFAULT_SORT_ORDER=_ID;

        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.com.example.contentprovider.notes";

        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.com.example.contentprovider.notes";

        public static final int NOTES = 1;

        public static final int NOTES_ID = 2;

 

        public static final String KEY_TITLE = "title";

        public static final String KEY_BODY = "body";

        public static final String KEY_ROWID = "_id";

   

    }

 

    static {

        uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);

        uriMatcher.addURI(PROVIDER_NAME, Notes.DATABASE_TABLE, Notes.NOTES);

        uriMatcher.addURI(PROVIDER_NAME, Notes.DATABASE_TABLE + "/#", Notes.NOTES_ID);

    }

 

    @Override

    public boolean onCreate() {

        notesDbAdapter = new NotesDbAdapter(getContext());

        notesDbAdapter.open();

        return false;

    }

 

    @Override

    public String getType(Uri uri) {

        switch (uriMatcher.match(uri)) {

        case Notes.NOTES:

            return Notes.CONTENT_TYPE;

        case Notes.NOTES_ID:

            return Notes.CONTENT_ITEM_TYPE;

        default:

            throw new IllegalArgumentException("Unsupported URI: " + uri);

        }

    }

 

    @Override

    public Cursor query(Uri uri, String[] projection, String selection,    String[] selectionArgs, String sortOrder) {

        Cursor c=null;

        switch (uriMatcher.match(uri)) {

        case Notes.NOTES:

            c = notesDbAdapter.fetchAllNotes();

            break;

        case Notes.NOTES_ID:

            c = notesDbAdapter.fetchNote(Integer.parseInt(uri.getPathSegments().get(1)));

            break;

        }

        return c;

    }

 

    @Override

    public Uri insert(Uri uri, ContentValues values) {

        String title = values.getAsString(Notes.KEY_TITLE);

        String body = values.getAsString(Notes.KEY_BODY);

        long rowID = notesDbAdapter.createNote(title,body);

        Uri _uri = null;

        if (rowID > 0) {

            _uri = ContentUris.withAppendedId(Notes.CONTENT_URI, rowID);

            getContext().getContentResolver().notifyChange(_uri, null);

        }

        return _uri;

    }

 

    @Override

    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

        Log.e("NotesContentProvider","ERROR update, update for colletion type is not implemented.");

        throw new IllegalArgumentException("Unknown URI " + uri);

    }

 

    @Override

    public int delete(Uri uri, String selection, String[] selectionArgs) {

        Log.e("NotesContentProvider","ERROR delete, update for colletion type is not implemented.");

        throw new IllegalArgumentException("Unknown URI " + uri);

        //return 0;

    }

}

 

HelloContentProvider2.java

package com.example.contentprovider;

 

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 HelloContentProvider2 extends Activity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        insert();

        read();

    }

/*

 *   Accessing Notes Content Provider

 */  

//  Create or Insert

    private void insert(){

        ContentValues values = new ContentValues();

        values.put(NotesContentProvider.Notes.KEY_TITLE, "DATA01");

        values.put(NotesContentProvider.Notes.KEY_BODY, "DATA01_BODY");

        Uri uri = getContentResolver().insert(NotesContentProvider.Notes.CONTENT_URI, values);

    }// insert

 

//    Retrieve

    private void read(){

        String resultStr = "";

        Uri uri = NotesContentProvider.Notes.CONTENT_URI;

 

        Cursor c = managedQuery(uri, null, null, null, "");

        if(c==null){

            Toast.makeText(this, "Null",Toast.LENGTH_LONG).show();

        }else

        if (c.moveToFirst()) {

            do {

                resultStr = c.getString(c.getColumnIndex(NotesContentProvider.Notes._ID))

                  + ", "+ c.getString(c.getColumnIndex(NotesContentProvider.Notes.KEY_TITLE))

                  + ", "+ c.getString(c.getColumnIndex(NotesContentProvider.Notes.KEY_BODY));

                Toast.makeText(this, resultStr,Toast.LENGTH_LONG).show();

            } while (c.moveToNext());

        }

    }// read

}

 

NotesContentProvider.java(改訂) 変更部分のみ

package com.example.contentprovider;

 

import android.content.ContentProvider;

import android.content.ContentUris;

import android.content.ContentValues;

import android.content.UriMatcher;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteQueryBuilder;

import android.net.Uri;

import android.provider.BaseColumns;

import android.text.TextUtils;

import android.util.Log;

 

import com.android.demo.notepad3.NotesDbAdapter_x1;

 

public class NotesContentProvider extends ContentProvider{

    public static final String PROVIDER_NAME="com.example.contentprovider.notes";

    private static final UriMatcher uriMatcher;

    private NotesDbAdapter_x1 notesDbAdapter;

    private SQLiteDatabase mDb;

 

    public static final class Notes implements BaseColumns {// _ID _COUNTが定義されている。    ...

    @Override

    public boolean onCreate() {

        notesDbAdapter = new NotesDbAdapter_x1(getContext());

        notesDbAdapter.open();

        mDb = notesDbAdapter.getMDb();

        return false;

    }

 

    ...

    @Override

    public Cursor query(Uri uri, String[] projection, String selection,    String[] selectionArgs, String sortOrder) {

        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();

        sqlBuilder.setTables(Notes.DATABASE_TABLE);

        if (uriMatcher.match(uri) == Notes.NOTES_ID)

            sqlBuilder.appendWhere(Notes._ID + " = "+ uri.getPathSegments().get(1));

        Cursor c = sqlBuilder.query(mDb, projection, selection,selectionArgs, null, null, sortOrder);

        c.setNotificationUri(getContext().getContentResolver(), uri);

        return c;

    }

 

    // Inserts a new record into the content provider.

    @Override

    public Uri insert(Uri uri, ContentValues values) {

        long rowID = mDb.insert(Notes.DATABASE_TABLE, "", values);

        Log.d("@G SQLConnectionFactory insert", " rowID=" + rowID);

        Uri _uri = null;

        if (rowID > 0) {

            _uri = ContentUris.withAppendedId(Notes.CONTENT_URI, rowID);

            getContext().getContentResolver().notifyChange(_uri, null);

        }

        return _uri;

    }

   

    //Updates an existing record from the content provider.

    @Override

    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {

        int count = 0;

        switch (uriMatcher.match(uri)) {

        case Notes.NOTES:

            count = mDb.update(Notes.DATABASE_TABLE, values, selection,selectionArgs);

            break;

 

        case Notes.NOTES_ID:

            count = mDb.update(Notes.DATABASE_TABLE, values, Notes._ID+ " = "+ uri.getPathSegments().get(1)

                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection+ ')' : ""), selectionArgs);

            break;

        default:

            throw new IllegalArgumentException("Unknown URI " + uri);

        }

        getContext().getContentResolver().notifyChange(uri, null);

        return count;   

    }

 

    // Deletes an existing record from the content provider.

    @Override

    public int delete(Uri uri, String selection, String[] selectionArgs) {

        int count = 0;

        switch (uriMatcher.match(uri)) {

            case Notes.NOTES:

                count = mDb.delete(Notes.DATABASE_TABLE, selection,selectionArgs);

                break;

            case Notes.NOTES_ID:

                String id = uri.getPathSegments().get(1);

                count = mDb.delete(Notes.DATABASE_TABLE, Notes._ID+ " = "+ id+ (!TextUtils.isEmpty(selection) ? " AND (" + selection+ ')' : ""), selectionArgs);

                break;

            default:

                throw new IllegalArgumentException("Unknown URI " + uri);

            }

            getContext().getContentResolver().notifyChange(uri, null);

        return count;

    }   

}

 

HelloContentProvider3.java

package com.example.contentprovider;

 

import android.app.Activity;

import android.content.ContentValues;

import android.database.Cursor;

import android.net.Uri;

import android.os.Bundle;

import android.util.Log;

import android.widget.Toast;

 

public class HelloContentProvider3 extends Activity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        deleteAll();

        insert();

        read();

        update();

        delete();

        read();

    }

/*

 *   Accessing Bug1 Content Provider

 */  

// delete all

    private static final String tag = "HelloContentProvider3";

    private Uri[] uris = new Uri[5];

    private void deleteAll(){

        int k = getContentResolver().delete(NotesContentProvider.Notes.CONTENT_URI, null, null);

        Log.d(tag,"deleteAll k=" + k);

    }// deleteAll

   

    //  Create or Insert

    private void insert(){

        int i;

        Uri uri;

        ContentValues values;

        for(i=0;i<uris.length;i++){

            values = new ContentValues();

            values.put(NotesContentProvider.Notes.KEY_TITLE, "DATA" + i);

            values.put(NotesContentProvider.Notes.KEY_BODY, "BODY" + i);

            uris[i] = getContentResolver().insert(NotesContentProvider.Notes.CONTENT_URI, values);

        }

    }// insert

    //  update

    private void update(){

        int i, k;

        Uri uri;

        ContentValues values;

        String selection = NotesContentProvider.Notes.KEY_TITLE + "=?";

        String[] args = {"DATA1"};

        values = new ContentValues();

        values.put(NotesContentProvider.Notes.KEY_TITLE, "DATA1-C");

        values.put(NotesContentProvider.Notes.KEY_BODY, "BODY1-C");

        k = getContentResolver().update(NotesContentProvider.Notes.CONTENT_URI, values,selection, args);

    }// insert

 

    //  update

    private void delete(){

        int i, k;

        Uri uri;

        ContentValues values;

        String selection = NotesContentProvider.Notes.KEY_TITLE + "=?";

        String[] args = {"DATA2"};

        k = getContentResolver().delete(NotesContentProvider.Notes.CONTENT_URI, selection, args);

    }// insert

//    Retrieve

    private void read(){

        String resultStr = "";

        Uri uri;

        Cursor c;

       

        uri = NotesContentProvider.Notes.CONTENT_URI;

        c = managedQuery(uri, null, null, null, "");

        printCursor("read all", c);

       

        c = managedQuery(uris[0], null, null, null, "");

        printCursor("read uri[0]", c);

       

    }// read

    // print Cursor

    private void printCursor(String title, Cursor c){

        Log.d(tag,title);

        if(c==null){

            Log.d(tag, "Null");

        }else

        if (c.moveToFirst()) {

            do {

                Log.d(tag

                  , c.getString(c.getColumnIndex(NotesContentProvider.Notes._ID))

                  + ", "+ c.getString(c.getColumnIndex(NotesContentProvider.Notes.KEY_TITLE))

                  + ", "+ c.getString(c.getColumnIndex(NotesContentProvider.Notes.KEY_BODY)));

            } while (c.moveToNext());

        }

    }

}

 

NotesDbAdapter_x1.java(追加部分のみ)

    public SQLiteDatabase getMDb() {

        return mDb;

    }

 

 

以上