当前位置:Gxlcms > 数据库问题 > 内容提供者 ContentResolver 数据库 示例 -1

内容提供者 ContentResolver 数据库 示例 -1

时间:2021-07-01 10:21:17 帮助过:3人阅读

技术分享
public class MainActivity extends ListActivity {    private TextView tv_info;    private EditText editText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        List<String> mData = new ArrayList<String>(Arrays.asList("获取所有数据""插入""删除""查找""更新"));        ListAdapter mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mData);        editText = new EditText(this);        editText.setHint("请输入要增删改查数据的Name");        editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);        editText.setPadding(0, 30, 0, 30);        editText.setGravity(Gravity.CENTER);        getListView().addFooterView(editText);        tv_info = new TextView(this);// 将内容显示在TextView中        tv_info.setTextColor(Color.BLUE);        tv_info.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);        tv_info.setPadding(20, 10, 20, 10);        getListView().addFooterView(tv_info);        setListAdapter(mAdapter);    }    @Override    protected void onListItemClick(ListView l, View v, int position, long id) {        PersonDao2 dao = new PersonDao2(this);        String content = editText.getText().toString().trim();        switch (position) {        case 0:            ArrayList<Person> list = dao.findAll();            tv_info.setText(list.toString());            break;        case 1:            tv_info.setText(dao.add(content, new Random().nextInt(10) + "") + "");            break;        case 2:            tv_info.setText(dao.delete(content) + "");            break;        case 3:            tv_info.setText(dao.find(content) + "");            break;        case 4:            tv_info.setText(dao.update(content, "呵呵") + "");            break;        }    }}

ContentProvider
/** 提供一些public的方法,让其他应用访问自己私有的文件。我们很少会自己来定义ContentProvider,因为我们很多时候都不希望自己应用的数据暴露给*/public class MyContentProvider extends ContentProvider {    private SQLiteDatabase db;    private static final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);// 参数表示匹配不成功时的返回值,这里为-1    // 主机名称    public static final String authority = "com.bqt.contentprovider.person";    // 定义一些静态全局常量    public static final int QUERY = 0;    public static final int INSERT = 1;    public static final int DELETE = 2;    public static final int UPDATE = 3;    // 给匹配器添加一些【匹配规则】,放在静态代码块中的作用:随类加载而优先加载,且只加载一次    static {        // 参数: authority 主机名 ,path 路径名, code 匹配码,匹配成功时的返回值        matcher.addURI(authority"query"QUERY);// 可以使用限定符*和#。* may be used as a wild card for any text, and # may be used as a wild card for numbers.        matcher.addURI(authority"insert"INSERT);//即Uri格式为【content://com.bqt.contentprovider.person/insert】        matcher.addURI(authority"delete"DELETE);        matcher.addURI(authority"update"UPDATE);    }    @Override    public boolean onCreate() {        MySQLiteOpenHelper helper = new MySQLiteOpenHelper(getContext());        db = helper.getWritableDatabase();        return true;//true if the provider was successfully loaded, false otherwise    }    @Override    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {        if (matcher.match(uri) == QUERY) {            //表名,要查询的列名数组,选择条件,选择条件对应的参数,分组,分组条件,排序            Cursor cursor = db.query(MySQLiteOpenHelper.TABLE_NAME, projection, selection, selectionArgs, nullnull, sortOrder);            return cursor;//Returns:A Cursor object, which is positioned before the first entry.        } else return null;    }    @Override    public int delete(Uri uri, String selection, String[] selectionArgs) {        if (matcher.match(uri) == DELETE) {            return db.delete(MySQLiteOpenHelper.TABLE_NAME, selection, selectionArgs);            //Returns:    the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause        } else throw new IllegalArgumentException("非法uri");    }    @Override    public Uri insert(Uri uri, ContentValues values) {        if (matcher.match(uri) == INSERT) {            long id = db.insert(MySQLiteOpenHelper.TABLE_NAMEnull, values);//Returns:    the row ID of the newly inserted row, or -1 if an error occurred            return ContentUris.withAppendedId(uri, id);//a new URI with the given ID appended to the end of the path        } else throw new IllegalArgumentException("非法uri");    }    @Override    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {        if (matcher.match(uri) == UPDATE) {            return db.update(MySQLiteOpenHelper.TABLE_NAME, values, selection, selectionArgs);//Returns:the number of rows affected        } else throw new IllegalArgumentException("非法uri");    }    @Override    /**MIME类型*/    public String getType(Uri uri) {        return "";//a MIME type string, or null if there is no type.    }}

SQLiteOpenHelper
/** 数据库【创建】或【打开】辅助类 */public class MySQLiteOpenHelper extends SQLiteOpenHelper {    public static final String DB_NAME = "person.db";    public static int DB_VERSION = 2;    //所有的表名及SQL語句都放到一個單獨的類中,这里图方便放到了这里    public static final String TABLE_NAME = "person";    public static final String CREATE_TABLE = "create table if not exists " + TABLE_NAME + " (id integer primary key autoincrement," + "name varchar,"            + "number varchar)";    public MySQLiteOpenHelper(Context context) {        super(context, DB_NAMEnullDB_VERSION);    }    @Override    public void onCreate(SQLiteDatabase db) {        db.execSQL(CREATE_TABLE);        //        db.execSQL(DBConstants.CREATE_PHOTO_TABLE);        //        db.execSQL(DBConstants.CREATE_DOWNLOAD_TABLE);        //        db.execSQL(DBConstants.CREATE_USER_TABLE);        //        db.execSQL(DBConstants.CREATE_GIFTS_TABLE);        //        db.execSQL(DBConstants.CREATE_ZIP_TABLE);    }    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        db.execSQL("drop table if exists " + TABLE_NAME);        //        db.execSQL("drop table if exists " + DBConstants.DB_PHOTO_TABLE);        //        db.execSQL("drop table if exists " + DBConstants.DB_DOWNLOAD_TABLE);        //        db.execSQL("drop table if exists " + DBConstants.DB_USER_TABLE);        //        db.execSQL("drop table if exists " + DBConstants.DB_GIFTS_TABLE);        //        db.execSQL("drop table if exists " + DBConstants.DB_ZIP_TABLE);        onCreate(db);    }}

DAO1
/** DAO(Data Access Object) 数据访问对象,是一个面向对象的数据库接口,夹在业务逻辑与数据库资源中间。相当于是数据库的【工具类】*/public class PersonDao {    private MySQLiteOpenHelper helper;    public PersonDao(Context context) {        helper = new MySQLiteOpenHelper(context);    }    public ArrayList<Person> findAll() {        SQLiteDatabase db = helper.getWritableDatabase();        ArrayList<Person> persons = new ArrayList<Person>();        Cursor cursor = db.rawQuery("select * from person"null);        //Returns:A Cursor object, which is positioned before the first entry.        while (cursor.moveToNext()) {            int id = cursor.getInt(cursor.getColumnIndex("id"));//获取指定列的值            String name = cursor.getString(cursor.getColumnIndex("name"));            String number = cursor.getString(cursor.getColumnIndex("number"));            Person p = new Person(id, name, number);            persons.add(p);        }        cursor.close();        db.close();        return persons;    }    public boolean find(String name) {        SQLiteDatabase db = helper.getWritableDatabase();        Cursor cursor = db.rawQuery("select * from person where name=?"new String[] { name });        boolean result = cursor.moveToNext();//结果集最初始时是指向表的最前面的,moveToNext时指向的才是【第一条】数据        cursor.close();        db.close();        return result;    }    public void add(String name, String number) {        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("insert into person(name,number) values(?,?)"new Object[] { name, number });        //Returns:    the row ID of the newly inserted row, or -1 if an error occurred        db.close();    }    public void update(String name, String newNumber) {        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("update person set number=? where name=?"new Object[] { newNumber, name });        //Returns:the number of rows affected        db.close();    }    public void delete(String name) {        SQLiteDatabase db = helper.getWritableDatabase();        db.execSQL("delete from person where name=?"new Object[] { name });        //Returns:    the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause        db.close();    }}

DAO2
public class PersonDao2 {    private MySQLiteOpenHelper helper;    public PersonDao2(Context context) {        helper = new MySQLiteOpenHelper(context);    }    public ArrayList<Person> findAll() {        SQLiteDatabase db = helper.getWritableDatabase();//数据库不作为成员变量的原因:1、使用完要及时关闭;2、关闭后必须重新通过helper打开。        //java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.bqt.contentprovider/databases/person.db        ArrayList<Person> persons = new ArrayList<Person>();        Cursor cursor = db.query("person"new String[] { "name""number""id" }, nullnullnullnullnull);        while (cursor.moveToNext()) {            int id = cursor.getInt(cursor.getColumnIndex("id"));            String name = cursor.getString(cursor.getColumnIndex("name"));            String number = cursor.getString(cursor.getColumnIndex("number"));            persons.add(new Person(id, name, number));        }        cursor.close();        db.close();        return persons;    }    public boolean find(String name) {        SQLiteDatabase db = helper.getWritableDatabase();        Cursor cursor = db.query("person"null"name=?"new String[] { name }, nullnullnull);        //要查询的表名,要查询的列名的数组(null代表所有列),选择条件(即WHERE语句,可以使用占位符 String[])        //选择条件中占位符的值(数组类型),分组语句(groupBy),having条件语句,排序语句(orderBy)        boolean result = cursor.moveToNext();//Returns:whether the move succeeded.        cursor.close();        db.close();        return result;    }    public long add(String name, String number) {        SQLiteDatabase db = helper.getWritableDatabase();        ContentValues values = new ContentValues();// 其实是一个map集合,里面保存的是每条记录的"键值对"信息        values.put("name", name);        values.put("number", number);        long id = db.insert("person"null, values);//返回新添加行的行号        db.close();        return id;    }    public int update(String name, String newNumber) {        SQLiteDatabase db = helper.getWritableDatabase();        ContentValues values = new ContentValues();                        

人气教程排行