【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到底是怎么存储数据的!

 

 

 

posted @   Rex..  阅读(72541)  评论(1编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示