JSONObject不会保存到SQL数据库

时间:2019-04-19 04:07:39

标签: android sql json

我正在使用Asyncs从网站下载并解析JSON,以保存在SQL数据库中。我已经成功下载了JSONArray并在我的logcat上验证了它的存在。但是,当我将JSONArray解析为 courseCode courseTitle 列时,然后将其存储到名为“ courses”的SQL表中……实际上没有任何保存。

我已经验证了使用内容值(名为“ menuValues”)下载的网站数据。我必须使用错误的方法保存到SQL数据库,还是不适合使用JSONArray对象?

 @Override
    protected String doInBackground(String... urls) {

        try {
            url = new URL(urls[0]);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        StringBuilder stringBuilder = new StringBuilder();
        HttpURLConnection urlConnection = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            InputStream content = new BufferedInputStream(
                    urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {

                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
        }
        return resulting = stringBuilder.toString();
    }



@RequiresApi(api = Build.VERSION_CODES.KITKAT)
protected void onPostExecute(String result) {

    databaseHelper databaseHelper = new databaseHelper(myActivity);
    SQLiteDatabase db=databaseHelper.getWritableDatabase();
    db.beginTransaction();
    try {
       String jsonDataString = resulting;  // Returned from doInBackGround
        JSONArray menuItemsJsonArray = new JSONArray(jsonDataString);

        db.beginTransaction();

        for(int i =0; i<menuItemsJsonArray.length(); i++){
            String courseCode;
            String courseTitle;

            JSONObject menuDataString = menuItemsJsonArray.getJSONObject(i);
            courseCode = menuDataString.getString("courseCode");
            courseTitle=menuDataString.getString("courseTitle");

            ContentValues menuValues = new ContentValues();
            menuValues.put("course_code1", courseCode);
            menuValues.put("course_name1", courseTitle);

            db.insert("courses", null, menuValues); // Not saving here
            Log.v("DATABASE INSERTION", "NEW ID " + menuValues); // Verified menuValues has correct info..... V/DATABASE INSERTION: NEW ID course_name1=Intro to Comp. course_code1=COMP9

        }
        db.setTransactionSuccessful();


    }catch(Exception e){
        Log.e("MESSAGE", e.getMessage(), e);
    }finally{
        db.endTransaction();

    }
    db.close();

}

0 个答案:

没有答案