creating Json from sqlite in Android

Viewed 6117

i want to have json file from my sqlite and save it in asset.myJson.json. following is my codes,i want to see result in myJson.json. please help me how to import data to myJson.json.

private JSONArray jsongetResult(){
    SQLiteDatabase database = openOrCreateDatabase("ORCL", MODE_PRIVATE, null);
    Cursor cursor = database.rawQuery("SELECT id,title,qty,price FROM CART;", null);

    JSONArray resultSet     = new JSONArray();

    cursor.moveToFirst();
    while (cursor.isAfterLast() == false) {

        int totalColumn = cursor.getColumnCount();
        JSONObject rowObject = new JSONObject();

        for( int i=0 ;  i< totalColumn ; i++ )
        {
            if( cursor.getColumnName(i) != null )
            {

                try
                {

                    if( cursor.getString(i) != null )
                    {
                        Log.d("TAG_NAME", cursor.getString(i) );
                        rowObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                    }
                    else
                    {
                        rowObject.put( cursor.getColumnName(i) ,  "" );
                    }
                }
                catch( Exception e )
                {
                    Log.d("TAG_NAME", e.getMessage()  );
                }
            }

        }

        resultSet.put(rowObject);

    }
    cursor.close();
    Log.d("TAG_NAME", resultSet.toString() );
    return resultSet;

}
2 Answers

I used the string concatenation operator to build my JSON (||) in the select clause in my raw query and it worked.

instead of

SELECT json_object('column1', column1, 'column2', column2) FROM table

use

SELECT "{" || "column1"  || ":" || column1 || || "," || "column2"  || ":" || column2 ||  "}" FROM table
Related