• 【Android】ContentValues的用法


    ContentValues 和HashTable类似都是一种存储的机制 但是两者最大的区别就在于,contenvalues只能存储基本类型的数据,像string,int之类的,不能存储对象这种东西,而HashTable却可以存储对象。

    在忘数据库中插入数据的时候,首先应该有一个ContentValues的对象所以:

    ContentValues initialValues = new ContentValues();

    initialValues.put(key,values);

    SQLiteDataBase sdb ;

    sdb.insert(database_name,null,initialValues);

    插入成功就返回记录的id否则返回-1;

    就可以插入一行数据,详细见下面代码

    public Uri insert(Uri uri, ContentValues initialValues) {
            if (uriMatcher.match(uri) != CONTACTS) {
                throw new IllegalArgumentException("unknow uri " + uri);
            }
            ContentValues values;
            if (initialValues != null) {
                values = new ContentValues(initialValues);
                System.out.println("contentValues插入成功,initailValues不是空的");
            } else {
                values = new ContentValues();
            }
            Long now = Long.valueOf(System.currentTimeMillis());
            // 设置默认值
            if (values.containsKey(ContactColumn.CREATED) == false) {
                values.put(ContactColumn.CREATED, now);
            }
    
            if (values.containsKey(ContactColumn.NAME) == false) {
                values.put(ContactColumn.NAME, now);
            }
    
            if (values.containsKey(ContactColumn.EMAIL) == false) {
                values.put(ContactColumn.EMAIL, now);
            }
    
            if (values.containsKey(ContactColumn.MOBILE) == false) {
                values.put(ContactColumn.MOBILE, now);
            }
    
            if (values.containsKey(ContactColumn.MODIFIED) == false) {
                values.put(ContactColumn.MODIFIED, now);
            }
            System.out.println("应该插入成功了吧");
            long RowId = contactsDB.insert(CONTACTS_TABLE, null, values);
            if (RowId > 0) {
                Uri noteUri = ContentUris.withAppendedId(CONTENT_URI, RowId);
                getContext().getContentResolver().notifyChange(noteUri, null);
                System.out.println("到这里也是没问题的!");
                return noteUri;
            }
            throw new IllegalArgumentException("unknow uri " + uri);
        }

    当然以上代码是根据Uri来操作的所以要想明白代码怎么回事?还要明白ContentProvider到底是怎么存储数据的!

  • 相关阅读:
    大数据学习13_MapReduce计数器&排序和序列化
    大数据学习12_MapReduce分区
    大数据学习11_MapReduce案例实战(单词统计)
    大数据学习10_Mapreduce
    大数据学习09_HDFS3
    周总结8
    《河北省重大技术需求征集系统》10_导入大量数据做测试
    《河北省重大技术需求征集系统》08_需求浏览
    《河北省重大技术需求征集系统》07_综合查询
    《河北省重大技术需求征集系统》06_网络审核
  • 原文地址:https://www.cnblogs.com/rayray/p/3410204.html
Copyright © 2020-2023  润新知