0

im beginner with android programming.I have simple problem.. and i dont know what to start with. I took someones else code. I need to get all information hold in this database table and convert it so json string. how may i do that ?

here's the code :

package com.project.sqlite;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseDataHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 3;

    // Database Name
    private static final String DATABASE_NAME = "simplify_1";

    // DATA table name
    private static final String TABLE_DATA = "FORMS";

    // DATA Table Columns names
    private static final String KEY_DATA_ID = "id";
    private static final String KEY_OBJECT_ID = "objectID";
    private static final String KEY_TYPE = "type";
    private static final String KEY_DATE = "date";
    private static final String KEY_JSON = "json";

    public DatabaseDataHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {   
        String CREATE_DATA_TABLE = "CREATE TABLE " + TABLE_DATA + "("
                + KEY_DATA_ID + " INTEGER PRIMARY KEY," + KEY_OBJECT_ID + " TEXT," + KEY_TYPE + " TEXT,"
                + KEY_DATE + " DATE," + KEY_JSON + " TEXT" + ")";
        db.execSQL(CREATE_DATA_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_DATA);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Add new DATA
    public void addData(Data data) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_OBJECT_ID, data.getObjectID());
        values.put(KEY_TYPE, data.getType());
        values.put(KEY_DATE, data.getDate());
        values.put(KEY_JSON, data.getJson());

        // Inserting Row
        db.insert(TABLE_DATA, null, values);
        db.close(); // Closing database connection
    }

    // Getting All DATA
    public List<Data> getAllData() {
        List<Data> dataList = new ArrayList<Data>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_DATA;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Data data = new Data();
                data.setID(Integer.parseInt(cursor.getString(0)));
                data.setObjectID(cursor.getString(1));
                data.setType(cursor.getString(2));
                data.setDate(cursor.getString(3));
                data.setJson(cursor.getString(4));
                // Adding contact to list
                dataList.add(data);
            } while (cursor.moveToNext());
        }

        // return user list
        return dataList;
    }


}

Here is my class in which i would like to do that:

import java.util.TimerTask;

import com.project.sqlite.DatabaseDataHandler;

import android.util.Log;

public class Data_synch extends TimerTask {
    DatabaseDataHandler db = new DatabaseDataHandler(this);
    @Override
    public void run() {

    }
    }

can you show me the right way ?

UPDATE i get an eror in this line :

DatabaseDataHandler db = new DatabaseDataHandler(this);

what context should be defined ??

4
  • Refer the link stackoverflow.com/questions/18857884/… to change your list into JSONArray and then call toString() to get the JSON string. Commented Apr 10, 2014 at 8:38
  • "this" is a keyword used to refer to the current instance. Here "this" is TimerTask not Activity. You have to pass either activity or application context. Commented Apr 10, 2014 at 9:04
  • How may i get context ? from where should i take it ? Commented Apr 10, 2014 at 9:18
  • you must be calling this from an activity. pass the getApplicationContext() from there in Data_Synch constructor or use a centralized application class for keeping context. Commented Apr 10, 2014 at 11:21

1 Answer 1

1

Have you tried google's gson to convert json object into java objects. It is great.

here's the download link gson 2.2.4

Just add this to your libs folder. In one line of code you can convert java objects to json and vice versa.

Sample:

let us say your json object is this

JSONObject myJson = {"name":"Tony Stark","group":"avengers","occupation":"superhero"}

your java class must have matching state names

class JsonToJAVA  {
    string name,
    string group,
    string occupation,
}

Here is how you convert in one line:

JsonToJAVA j = gson.fromJson(myJson.toString(), JsonToJAVA.class);

just initialize the gson somewhere

Gson gson = new Gson();

there you have an instance of your class (j above) representing the json. Feel free to add getters setters or any other method you want inside the JsonToJAVA class.

There is another method toJson() in GSON to convert java class into json.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.