我正在使用web service
以JSON
格式返回数据,如下所示:
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
onCreate()
的{p> MainActivity.java
是:
boolean myFlag = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
setFlag = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
dataSource = new ContentsDataSource(this);
dataSource.open();
parseAndIsertData();
}
parseAndInsertData()
是:
EDIT
private void parseAndIsertData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
contentDataObject = new ContentDataObject();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// first time check if data is inserted
editor = setFlag.edit();
editor.putBoolean(MY_KEY, true);
// Getting Array of Contents
jsonArray = json.getJSONArray(MOBILE_CONTENT);
// looping through All Contents
if(!myFlag){
for(int i = 0; i < jsonArray.length(); i++){
contentDataObject.setId(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_ID));
contentDataObject.setTitle(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_TITLE));
contentDataObject.setFulltext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_FULLTEXT));
contentDataObject.setState(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_STATE));
contentDataObject.setNewValue(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_NEW));
contentDataObject.setHeader(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_HEADER));
contentDataObject.setColor(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_COLOR));
contentDataObject.setNext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_NEXT));
contentDataObject.setPrevious(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_PREVIOUS));
contentDataObject = dataSource.create(contentDataObject);
Log.i(MY_TAGT, "Data Inserted " + contentDataObject.getId() + " Times");
}
myFlag = setFlag.getBoolean(MY_KEY, false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
现在我的logcat
首次启动时是:
当我重新启动应用时,我的logcat
是:
现在我想问一下,如果YES
,这种方法是否正确!然后我将能够在以后更新!!
谢谢!
答案 0 :(得分:0)
您是正确的,此代码将多次插入数据。由您来实现只允许一行的模式。
您需要首先查询数据源,如果数据存在则不插入数据,或者您需要从数据源中删除数据,然后每次都插入数据。还有其他模式,但这两种模式最常见。您选择哪一个取决于数据是什么以及您希望如何维护或更新数据。
答案 1 :(得分:0)
primary key
或unique
SQLiteDatabase.insertWithOnConflict(...)
将conflictAlgorithm
参数(最后一个)设置为``SQLiteDatabase.CONFLICT_IGNORE` 请参阅this