这就是我的代码应该如何工作的方式!
第一步正如我缩进一样工作。问题是,第二步不起作用。我认为json_data对象没有传递给插入数据的dbCodeHelper类!
以下是相应的代码部分:
//dbConnection class
JSONObject json_data;
dbCodeHelper db = new dbCodeHelper();
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getString("facts"));
db.addAllFacts(json_data);
}
Log.i("log_tag","facts: "+json_data.getString("facts"));
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
...
//from dbCodeHelper Class
public void addAllFacts(JSONObject json_data)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
try {
values.put(KEY_SL_NUMBER, json_data.getInt("sl_number"));
values.put(KEY_NAME, json_data.getString("facts"));
db.insert(TABLE_NAME, null, values);
db.close();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("log_tag","id: "+ "something messed up in the dbcodehlper class(inserting all the data)!!!");
}
}
//from mainactivity
protected void onResume() {
super.onResume();
if (prefs.getBoolean("firstrun", true)) {
//getDbData(prefs);
// Do first run stuff here then set 'firstrun' as false
// using the following line to edit/commit prefs
prefs.edit().putBoolean("firstrun", false).commit();
}
connectionDb cdb = new connectionDb();
cdb.execute("http://coolfacts.in/app/dbconnectservice.php");
}
答案 0 :(得分:1)
为了在您的DBHelper类中传递您的上下文,您可以按照以下网站上列出的答案进行操作:Using Application context everywhere?