程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 編程-自定義ContentProvider,書上這個代碼怎麼改?

編程-自定義ContentProvider,書上這個代碼怎麼改?

編輯:編程解疑
自定義ContentProvider,書上這個代碼怎麼改?

DataBaseHelpe.java

 package com.example.definecontentprovider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelpe extends SQLiteOpenHelper{
    public static final String DB_NAME="userdb.db";
    public static final String TABLENAME="userinfo";
    public static final int DB_VERSION=1;
    public static final String CREATETABLE="create table"+TABLENAME+"(_id integer primary key,username text,userpassword text);";

    public DataBaseHelpe(Context context)
    {
        super(context,DB_NAME,null,DB_VERSION);
    }

    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(CREATETABLE);
    }

    public void onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)
    {
        Log.i("Database update......","Update database from"+oldVersion+"to"+newVersion);
        db.execSQL("drop table if it exists"+TABLENAME);
        onCreate(db);
    }


}

MainActivity.java

 package com.example.definecontentprovider;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ContentResolver cr=getContentResolver();
        //增加記錄
        ContentValues values=new ContentValues();
        values.put("username","admin");
        values.put("userpassword","123456");
        cr.insert(UserProvider.CONTENT_URI, values);
        values.clear();
        values.put("username","zhangsan");
        values.put("userpassword","666666");
        cr.insert(UserProvider.CONTENT_URI, values);
        //查詢所有記錄
        Cursor cursor=cr.query(UserProvider.CONTENT_URI, null, null, null, null);
        Log.i("after inserted","-------------------------");
        while(cursor.moveToNext()){
            Log.i("after inserted","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));

        }
        cursor.close();
        //修改記錄
        values.clear();
        values.put("username","lisi");
        //構建的Uri為:"content://com.chapt6.userprovider/userinfo/2"
        Uri uri=ContentUris.withAppendedId(UserProvider.CONTENT_URI,2);
        //修改id為2的記錄
        cr.update(uri, values, null, null);
        //查詢id為2的記錄
        cursor=cr.query(uri, null, null, null, null);
        Log.i("after updated","-------------------------");
        while(cursor.moveToNext()){
            Log.i("after updated","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));

        }
        cursor.close();
        //刪除id為2的記錄
        cr.delete(uri, null, null);
        //查詢記錄
        cursor=cr.query(UserProvider.CONTENT_URI, null, null, null, null);
        Log.i("after deleted","-------------------------");
        while(cursor.moveToNext()){
            Log.i("after deleted","id:"+cursor.getString(0)+"username:"+cursor.getString(1)+"userpassword:"+cursor.getString(2));

        }
        cursor.close();

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

UserProvider.java

 package com.example.definecontentprovider;

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.net.Uri;

public class UserProvider extends ContentProvider{
    private DataBaseHelper dbh=null;
    //發布Content Provider的Uri地址
    private static final String AUTHORITY="com.chapt6.userprovider";
    public static final Uri CONTENT_URI=Uri.parse("content://com.chapt6.userprovider/userinfo");
    //注冊需要匹配的Uri
    private static UriMatcher uriMatcher=new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(AUTHORITY, "userinfo",1);
        uriMatcher.addURI(AUTHORITY, "userinfo/#",2);
    }
    //該方法在ContentProvider創建後就會被調用,在其他應用第一次訪問它時才會被創建
    public boolean onCreate(){
        dbh=new DataBaseHelper(getContext());
        return false;
    }
    //該方法用於返回當前Uri所代表數據的MIME類型
    public String getType(Uri uri){
        switch (uriMatcher.match(uri)){
        case 1:
            return "vnd.android.cursor.dir/userinfo";
        case 2:
            return "vnd.android.cursor.item/userinfo";
        }
        return null;
    }
    //該方法用於供外部應用從ContentProvider刪除數據
    public int delete(Uri uri,String selection,String[] selectionArgs){
        SQLiteDatabase db=dbh.getWritableDatabase();
        int num=0;
        switch(uriMatcher.match(uri)){
        case 1:
            num=db.delete("userinfo",selection,selectionArgs);
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            if(selection==null){
                selection="_id="+id;
            }
            else{
                selection="_id="+id+" and ("+selection+")";
            }
            num=db.delete("userinfo",selection,selectionArgs);
            break;
        default:
            break;
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return num;
    }
    //該方法用於供外部應用往ContentProvider添加數據
    public Uri insert(Uri uri,ContentValues values){
        SQLiteDatabase db=dbh.getWritableDatabase();
        long id=db.insert("userinfo", null, values);
        if(id>-1)//插入數據成功
        {//構建新插入行的Uri
            Uri insertUri=ContentUris.withAppendedId(CONTENT_URI, id);
            //通知所有的觀察者,數據集已經改變
            getContext().getContentResolver().notifyChange(insertUri, null);
            return insertUri;
        }
        return null;
    }
    //該方法用於供外部應用從ContentProvider中獲取數據
    public Cursor query(Uri uri,String[] projection,String selection,String[] selectionArgs,String sortOrder){
        SQLiteDatabase db=dbh.getReadableDatabase();
        Cursor cursor=null;
        switch(uriMatcher.match(uri)){
        case 1:
            cursor=db.query("userinfo",//表名
                    null,//列的數組,null代表所有列
                    selection,//where條件
                    selectionArgs,//where條件的參數值的數組
                    null,//分組
                    null,//having
                    sortOrder);//排序規則
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            if(selection==null){
                selection="_id="+id;
            }
            else{
                selection="_id="+id+" and ("+selection+")";
            }
            cursor=db.query("userinfo",
                    null,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder);
            break;
        default:
            break;
        }
        return cursor;
    }
    //該方法用於供外部應用更新ContentProvider中的數據
    public int update(Uri uri,ContentValues values,String selection,String[] selectionArgs){
        SQLiteDatabase db=dbh.getWritableDatabase();
        int num=0;
        switch(uriMatcher.match(uri)){
        case 1:
            num=db.update("userinfo",values,selection,selectionArgs);
            break;
        case 2:
            long id=ContentUris.parseId(uri);
            //在selection上增加條件_id=id
            if(selection==null){
                selection="_id="+id;
            }
            else{
                selection="_id="+id+" and ("+selection+")";
            }
            num=db.update("userinfo",values,selection,selectionArgs);
            break;
        default:
            break;
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return num;
    }

}

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.definecontentprovider"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name=".UserProvider"
            android:authorities=".userprovider"
            android:exported="true">

        </provider>
    </application>

</manifest>

圖片說明
圖片說明
圖片說明

最佳回答:


DataBaseHelpe 你類名拼寫錯誤,或者你就按照這個錯誤的類名來引用

YXTS122
oSanYeCao1234567
YXTS122
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved