从XML文件填充SQLite数据库时数据错乱求助
解决XML导入SQLite数据错乱的问题
嘿,我一眼就看出问题出在哪了——你用索引位置来获取XML属性值的方式踩坑了!XmlPullParser并不会严格按照你在XML里写的属性顺序返回索引对应的内容(从你的实际结果来看,path和man的属性值直接颠倒了,说明索引0对应的是man而不是你以为的path),这就导致数据插错了位置。
最稳妥的修复方法:按属性名称取值
别依赖索引了,直接通过属性的名字来获取对应的值,不管XML里属性顺序怎么变,都能精准拿到数据。修改你解析XML的代码段:
if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("record"))) { // 替换索引获取为名称匹配 String path = _xml.getAttributeValue(null, "path"); String man = _xml.getAttributeValue(null, "man"); String woman = _xml.getAttributeValue(null, "woman"); values.put("path", path); values.put("man", man); values.put("woman", woman); db.insert("mytable", null, values); Log.d(LOG_TAG, "success"); }
额外的小优化
还有个细节可以完善下:你现在是在循环外面初始化的ContentValues values,虽然当前逻辑没出问题,但最好每次处理一个<record>标签时都新建一个ContentValues对象,防止万一之前的数据残留影响后续插入:
if ((eventType == XmlPullParser.START_TAG) && (_xml.getName().equals("record"))) { // 每次处理记录都新建ContentValues,避免数据残留 ContentValues values = new ContentValues(); String path = _xml.getAttributeValue(null, "path"); String man = _xml.getAttributeValue(null, "man"); String woman = _xml.getAttributeValue(null, "woman"); values.put("path", path); values.put("man", man); values.put("woman", woman); db.insert("mytable", null, values); Log.d(LOG_TAG, "success"); }
这样改完之后,数据库里的数据就会和你预期的完全一致啦!
内容的提问来源于stack exchange,提问作者Sopelus
相关产品推荐
相关产品推荐

