Android sqlite tables to json file -
i new json. trying 2 sqlite tables json text file. able fetch each table , send text file results invalid if try read string file.
here code:
file f = new file(constants.default_backup_file_path); fileoutputstream fos = new fileoutputstream(f,true); printstream ps = new printstream(fos); string query1 = "select " + col_1 + "," + col_2 + " " + table_1; cursor cursor1 = db.rawquery(query1, null); cursor1.movetofirst(); jsonobject mobject = new jsonobject(); jsonarray tab1array = new jsonarray(); int = 0; while (!cursor1.isafterlast()) { jsonobject robject = new jsonobject(); try { robject.put("id", cursor1.getstring(cursor1.getcolumnindex(col_1))); robject.put("user", cursor1.getstring(cursor1.getcolumnindex(col_2))); cursor1.movetonext(); tab1array.put(i, robject); i++; } catch (jsonexception e) { e.printstacktrace(); } } mobject.put("table1", tab1array); ps.append(mobject.tostring()); string query2 = "select " + col_1 + "," + col_2 + " " + table_2; cursor cursor2 = db.rawquery(query2, null); cursor2.movetofirst(); jsonobject mobject2 = new jsonobject(); jsonarray tab2array = new jsonarray(); int i2 = 0; while (!cursor2.isafterlast()) { jsonobject robject2 = new jsonobject(); try { robject2.put("id", cursor2.getstring(cursor2.getcolumnindex(col_1))); robject2.put("name", cursor2.getstring(cursor2.getcolumnindex(col_2))); cursor2.movetonext(); tab2array.put(i2, robject2); i2++; } catch (jsonexception e) { e.printstacktrace(); } } mobject2.put("table2", tab1array); ps.append(mobject2.tostring());
my text file looks (note no comma between two):
{"table1":[{"id":"1", "user":"larry"},{"id":"2", "user":"mo"},{"id":"4", "user":"curly"},{"id":"5", "user":"shemp"}]} {"table2":[{"id":"1", "name":"ticky"},{"id":"2", "name":"tky"},{"id":"4", "name":"tem"},{"id":"5", "name":"bo"}]}
it should like: { "table1": [{ "id": "1", "user": "larry" }, { "id": "2", "user": "mo" }, { "id": "4", "user": "curly" }, { "id": "5", "user": "shemp" }], "table2": [{ "id": "1", "name": "ticky" }, { "id": "2", "name": "tky" }, { "id": "4", "name": "tem" }, { "id": "5", "name": "bo" }] }
i can parse table1 by:
try { jsonobject jsonobject = new jsonobject(backup); jsonarray jsonarray = jsonobject.getjsonarray("table1"); (int i=0;i<jsonarray.length();i++) { jsonobject jsonobject1 = jsonarray.getjsonobject(i); string theid = jsonobject1.getstring("_id");
but table2 can't found using same code. great in building exporting tables correctly.
remove ps.append(mobject.tostring());
middle of code, , change last 2 lines to:
mobject.put("table2", tab2array); ps.append(mobject.tostring());
Comments
Post a Comment