代码改变世界

Android ContentProvider 填删改查 实例

2011-05-25 17:51  闫妍  阅读(228)  评论(0编辑  收藏  举报

 

ContentProvider 操作类


import java.util.Calendar;
import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
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.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.eoeAndroid.contentProvider.Diary.DiaryColumns;

//继承自ContentProvider
public class DiaryContentProvider extends ContentProvider {

    private static final String DATABASE_NAME = "database";
    private static final int DATABASE_VERSION = 3;
    private static final String DIARY_TABLE_NAME = "diary";

    private static final int DIARIES = 1;
    private static final int DIARY_ID = 2;

    private static final UriMatcher sUriMatcher; //URi 操作类

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Log.i("jinyan", "DATABASE_VERSION=" + DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i("jinyan", "onCreate(SQLiteDatabase db)");
            String sql = "CREATE TABLE " + DIARY_TABLE_NAME + " ("
                    + DiaryColumns._ID + " INTEGER PRIMARY KEY,"
                    + DiaryColumns.TITLE + " TEXT," + DiaryColumns.BODY
                    + " TEXT," + DiaryColumns.CREATED + " TEXT" + ");";
            //
            sql ="CREATE TABLE " + DIARY_TABLE_NAME + " ("
            + DiaryColumns._ID + " INTEGER PRIMARY KEY,"
            + DiaryColumns.TITLE + " varchar(255)," + DiaryColumns.BODY
            + " TEXT," + DiaryColumns.CREATED + " TEXT" + ");";
            //
            Log.i("jinyan", "sql="+sql);
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i("jinyan",
                    " onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)="
                            + newVersion);
            db.execSQL("DROP TABLE IF EXISTS diary");
            onCreate(db);
        }
    }

    private DatabaseHelper mOpenHelper;

    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Diary.AUTHORITY, "diaries", DIARIES);//添加解析规则1
        sUriMatcher.addURI(Diary.AUTHORITY, "diaries/#", DIARY_ID);//添加解析规则2

    }

    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }

    //以下是重载实现接口方法
    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
        case DIARIES:
            qb.setTables(DIARY_TABLE_NAME);
            break;

        case DIARY_ID:
            qb.setTables(DIARY_TABLE_NAME);
            qb.appendWhere(DiaryColumns._ID + "="
                    + uri.getPathSegments().get(1));
            break;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = Diary.DiaryColumns.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }

        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        Cursor c = qb.query(db, projection, selection, selectionArgs, null,
                null, orderBy);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        switch (sUriMatcher.match(uri)) {
        case DIARIES:
            return DiaryColumns.CONTENT_TYPE;

        case DIARY_ID:
            return DiaryColumns.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues initialValues) {
        if (sUriMatcher.match(uri) != DIARIES) {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }

        ContentValues values;
        if (initialValues != null) {
            values = new ContentValues(initialValues);
        } else {
            values = new ContentValues();
        }

        if (values.containsKey(Diary.DiaryColumns.CREATED) == false) {
            values.put(Diary.DiaryColumns.CREATED, getFormateCreatedDate());
        }

        if (values.containsKey(Diary.DiaryColumns.TITLE) == false) {
            Resources r = Resources.getSystem();
            values.put(Diary.DiaryColumns.TITLE, r
                    .getString(android.R.string.untitled));
        }

        if (values.containsKey(Diary.DiaryColumns.BODY) == false) {
            values.put(Diary.DiaryColumns.BODY, "");
        }

        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        long rowId = db.insert(DIARY_TABLE_NAME, DiaryColumns.BODY, values);
        if (rowId > 0) {
            Uri diaryUri = ContentUris.withAppendedId(
                    Diary.DiaryColumns.CONTENT_URI, rowId);
            return diaryUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(Uri uri, String where, String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String rowId = uri.getPathSegments().get(1);
        return db
                .delete(DIARY_TABLE_NAME, DiaryColumns._ID + "=" + rowId, null);

    }

    @Override
    public int update(Uri uri, ContentValues values, String where,
            String[] whereArgs) {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        String rowId = uri.getPathSegments().get(1);
        return db.update(DIARY_TABLE_NAME, values, DiaryColumns._ID + "="
                + rowId, null);

    }

    public static String getFormateCreatedDate() {
        Calendar calendar = Calendar.getInstance();
        String created = calendar.get(Calendar.YEAR) + "年"
                + calendar.get(Calendar.MONTH) + "月"
                + calendar.get(Calendar.DAY_OF_MONTH) + "日"
                + calendar.get(Calendar.HOUR_OF_DAY) + "时"
                + calendar.get(Calendar.MINUTE) + "分";
        return created;
    }
}

基本信息配置类


import android.net.Uri;
import android.provider.BaseColumns;


public final class Diary {
    //这里的 AUTHORITY 要求是唯一,而且和Manifest当中provider标签的AUTHORITY内容一致
    public static final String AUTHORITY = "com.ex09_2_contentprovider.diarycontentprovider";

    private Diary() {}
   
    /**
     * Notes table
     */
    public static final class DiaryColumns implements BaseColumns {
        // This class cannot be instantiated
        private DiaryColumns() {}

        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/diaries");


        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.diary";


        public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.google.diary";


        public static final String DEFAULT_SORT_ORDER = "created DESC";

        public static final String TITLE = "title";

        public static final String BODY = "body";

        public static final String CREATED = "created";


    
    }
}

 

主页面列表

 

public class ActivityMain extends ListActivity {

    // 插入一条新纪录
    public static final int MENU_ITEM_INSERT = Menu.FIRST;
    // 编辑内容
    public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;
    public static final int MENU_ITEM_DELETE = Menu.FIRST + 2;

    private static final String[] PROJECTION = new String[] { DiaryColumns._ID,
            DiaryColumns.TITLE, DiaryColumns.CREATED };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diary_list);
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(DiaryColumns.CONTENT_URI);
        }
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null,
                null, DiaryColumns.DEFAULT_SORT_ORDER);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
                        DiaryColumns.CREATED }, new int[] { R.id.text1,
                        R.id.created });
        setListAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert);
        return true;
    }

    @Override
    /*
     * 在每一次menu生成的时候前都会调用这个方法,在这个方法里边可以动态的修改生成的menu。
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        final boolean haveItems = getListAdapter().getCount() > 0; //是否有数据
        if (haveItems) {
            // 如果选中一个Item的话
            if (getListView().getSelectedItemId() > 0) {
                menu.removeGroup(1); //移除分组为一的选项也就是添加的那个按钮
                Uri uri = ContentUris.withAppendedId(getIntent().getData(),
                        getSelectedItemId());
                Intent intent = new Intent(null, uri); //跳转地址
                menu.add(1, MENU_ITEM_EDIT, 1, "编辑内容").setIntent(intent);//添加两个按钮,组ID为1
                menu.add(1, MENU_ITEM_DELETE, 1, "删除当前日记");
            }

        }else{
            menu.removeGroup(1);
        }
        return true;
    }

    //点选后的回调事件。
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // 插入一条数据
        case MENU_ITEM_INSERT:
            Intent intent0 = new Intent(this, ActivityDiaryEditor.class);
            intent0.setAction(ActivityDiaryEditor.INSERT_DIARY_ACTION);
            intent0.setData(getIntent().getData());
            startActivity(intent0);
            return true;
            // 编辑当前数据内容
        case MENU_ITEM_EDIT:
            Intent intent = new Intent(this, ActivityDiaryEditor.class);
            intent.setData(item.getIntent().getData());
            intent.setAction(ActivityDiaryEditor.EDIT_DIARY_ACTION);
            startActivity(intent);
            return true;
            // 删除当前数据
        case MENU_ITEM_DELETE:
            Uri uri = ContentUris.withAppendedId(getIntent().getData(),
                    getListView().getSelectedItemId());
            getContentResolver().delete(uri, null, null);
            renderListView();

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
        startActivity(new Intent(ActivityDiaryEditor.EDIT_DIARY_ACTION, uri));

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //renderListView();
    }

    private void renderListView() {
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION, null,
                null, DiaryColumns.DEFAULT_SORT_ORDER);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
                        DiaryColumns.CREATED }, new int[] { R.id.text1,
                        R.id.created });
        setListAdapter(adapter);
    }
}

 

编辑页面

 


import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.eoeAndroid.contentProvider.Diary.DiaryColumns;

public class ActivityDiaryEditor extends Activity {
    private static final String TAG = "Diary";
    public static final String EDIT_DIARY_ACTION = "com.ex09_2_contentProvider.ActivityDiaryEditor.EDIT_DIARY";
    public static final String INSERT_DIARY_ACTION = "com.ex09_2_contentProvider.ActivityDiaryEditor.action.INSERT_DIARY";

    /**
     * 查询cursor时候,感兴趣的那些条例。
     */
    private static final String[] PROJECTION = new String[] { DiaryColumns._ID, // 0
            DiaryColumns.TITLE, DiaryColumns.BODY, // 1
    };

    private static final int STATE_EDIT = 0;
    private static final int STATE_INSERT = 1;

    private int mState;

    private Uri mUri;
    private Cursor mCursor;

    private EditText mTitleText;
    private EditText mBodyText;
    private Button confirmButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_Black);
        final Intent intent = getIntent();
        final String action = intent.getAction();
        setContentView(R.layout.diary_edit);
       
        mTitleText = (EditText) findViewById(R.id.title);
        mBodyText = (EditText) findViewById(R.id.body);
        confirmButton = (Button) findViewById(R.id.confirm);

        if (EDIT_DIARY_ACTION.equals(action)) {// 编辑日记
            mState = STATE_EDIT;
            mUri = intent.getData();
            mCursor = managedQuery(mUri, PROJECTION, null, null, null);
            mCursor.moveToFirst();
            String title = mCursor.getString(1);
            mTitleText.setTextKeepState(title);
            String body = mCursor.getString(2);
            mBodyText.setTextKeepState(body);
            setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
            setTitle("编辑日记");
        } else if (INSERT_DIARY_ACTION.equals(action)) {// 新建日记
            mState = STATE_INSERT;
            setTitle("新建日记");
        } else {
            Log.e(TAG, "no such action error");
            finish();
            return;
        }

        confirmButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (mState == STATE_INSERT) {
                    insertDiary();
                } else {
                    updateDiary();
                }
                Intent mIntent = new Intent();
                setResult(RESULT_OK, mIntent);
                finish();
            }

        });

    }

    private void insertDiary() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        ContentValues values = new ContentValues();
        values.put(Diary.DiaryColumns.CREATED, DiaryContentProvider
                .getFormateCreatedDate());
        values.put(Diary.DiaryColumns.TITLE, title);
        values.put(Diary.DiaryColumns.BODY, body);
        getContentResolver().insert(Diary.DiaryColumns.CONTENT_URI, values);

    }

    private void updateDiary() {
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        ContentValues values = new ContentValues();
        values.put(Diary.DiaryColumns.CREATED, DiaryContentProvider
                .getFormateCreatedDate());
        values.put(Diary.DiaryColumns.TITLE, title);
        values.put(Diary.DiaryColumns.BODY, body);
        getContentResolver().update(mUri, values,
                null, null);

    }
}