I am making an android app and have to save JSON to an SQLite database. The app already has a function to get JSON and display this in a listview and a function to save data to a database. Now I want to combine those, but I am a little lost.
public void get_data(String data) { try { JSONArray data_array=new JSONArray(data); for (int i = 0 ; i < data_array.length() ; i++) { JSONObject obj=new JSONObject(data_array.get(i).toString()); Courses add=new Courses(); add.name = obj.getString("name"); add.ects = obj.getString("ects"); add.grade = obj.getString("grade"); add.period = obj.getString("period"); courses.add(add); } adapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } This loops through the JSON so I think this is where is should save to the database.
public boolean insertCourse(String course, int ects, int period, int grade) { SQLiteDatabase db = getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COURSE_COLUMN_COURSE, course); contentValues.put(COURSE_COLUMN_ECTS, ects); contentValues.put(COURSE_COLUMN_PERIOD, period); contentValues.put(COURSE_COLUMN_GRADE, grade); db.insert(COURSE_TABLE_NAME, null, contentValues); return true; } This is in a DBHelper.class should be able to use this I think.
I was hoping to reuse the code which i used to save input fields to the database but no luck so far.
else { if(dbHelper.insertCourse(courseEditText.getText().toString(), Integer.parseInt(ectsEditText.getText().toString()), Integer.parseInt(periodEditText.getText().toString()), Integer.parseInt(gradeEditText.getText().toString()))) { Toast.makeText(getApplicationContext(), "Course Inserted", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(getApplicationContext(), "Could not Insert course", Toast.LENGTH_SHORT).show(); } Does anyone have a suggestion how to integrate both (if possible at all). Thnx in advance
EDIT: the logcat crash report:
04-09 17:45:37.204 12244-12244/com.stefspakman.progress2 E/AndroidRuntime: FATAL EXCEPTION: main Process: com.stefspakman.progress2, PID: 12244 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.stefspakman.progress2.ProgressDBHelper.insertCourse(java.lang.String, int, int, int)' on a null object reference at com.stefspakman.progress2.gradingActivity.get_data(gradingActivity.java:60) at com.stefspakman.progress2.Download_data$1.handleMessage(Download_data.java:58) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5422) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
insertCoursemethod when you extract the data from JSON .