Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQlite to json

I have some data stored inside SQlite at my android application and I want to export it into json file and send it to a server via post HTTP. You can actually see my code in this link - Old question containing my code

After searching the web, I'm only finding samples of doing it the other way around (from json to sqlite). I'll be happy to receive some help/push to the right direction.

Edit -

I get a small exeption while trying to initilise Gson - String json = gson.toJson(Record); . Can you take a look please -

public ArrayList<Record> getAllRecordsArray() {
        ArrayList<Record> localList = new ArrayList<Record>();

        String selectQuery = "SELECT * FROM " + TABLE_RECORD;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        //Loops through all rows and adds them to the local list
        if(cursor.moveToFirst())
        {
            do {
                //Get record information
                Record record = new Record();
                record.setpLat(cursor.getDouble(0));
                record.setpLong(cursor.getDouble(1));
                record.setpAcc(cursor.getFloat(2));
                record.setpTime(cursor.getLong(2));
                //Add record  to list
                localList.add(record);
            } while (cursor.moveToNext());
        }

        return localList;
    }

    Gson gson = new Gson();
    String json = gson.toJson(Record);
like image 812
GeoRay Avatar asked Apr 10 '26 16:04

GeoRay


2 Answers

Using the GSON library is by far the easiest way of handling it.

1) Initilize an ArrayList
2) Retrieve all the data from your database and store it in the ArrayList
3) Use gson.toJson(NameOfArrayList);
4) DONE. You now have a string containing all the data from your database.

like image 175
Moonbloom Avatar answered Apr 12 '26 05:04

Moonbloom


Have you considered using a library such as Gson? It allows you to easily convert a POJO (Plain old java object) to JSON.

You can simply get your object form your db and then do the following.

MyObject obj = new MyObject();
Gson gson = new Gson();
String json = gson.toJson(obj); 

Its very useful, here is a link to the user guide: https://sites.google.com/site/gson/gson-user-guide

Good Luck!

like image 42
DejanRistic Avatar answered Apr 12 '26 06:04

DejanRistic