只有一次我使用的是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"}]}
的MainActivity.java
onCreate()
是:
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
!那麼我將能夠在以後更新! 謝謝!
使用[UNIQUE約束](http://www.sqlite.org/syntaxdiagrams.html#column-constraint)創建ur表,以避免在插入d後重復插入列 – 2013-03-04 17:56:38
ata in db在'SharedPreferences'中存儲了一些標誌,就像如果成功插入一樣,然後存儲true否則爲false,並且在從服務器請求數據之前存儲true的Activity的oncreate中檢查SharedPreferences標誌值,如果爲true,則表示不需要再次請求或者如果爲false,則請求服務器 – 2013-03-04 18:02:44
我已經嘗試了很多次,但是如果你可以給我一些例子,我不能得到結果! – 2013-03-05 15:50:16