有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图从JSON数组向数据库插入数据

这就是我的代码的工作原理

  1. 使用php向mysql数据库发出http post(在AyncTask类中),以获取json编码的数据
  2. 从dbCodeHelper类中的每一行1乘1获取json编码的数据(该类完成了在安卓设备上处理数据库所需的所有操作。(插入新行和所有行)

第一步完全按照我的缩进进行。问题是,第二步不起作用。我认为json_数据对象没有被传递到发生插入数据的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");
}

共 (1) 个答案