Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert cursor object to XML or JSON in android

Is there any libraries are available to convert Cursor object to direct XML or JSON .

For example , we have a table with two columns id,name. When i get cursor object from DB. With out looping cursor i want to convert it into

<XML>
<id>1<id>
<name>xyz</name>
</XML>

Thanks in advance.

like image 497
Santhi Bharath Avatar asked Sep 18 '25 00:09

Santhi Bharath


2 Answers

Use this:

JSONArray array = new JSONArray();
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            JSONObject object = new JSONObject();
            try {
                object.put("id", cursor.getString(0));
                object.put("name", cursor.getString(1));
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

And if you want to create a XML data than use this: Link. Hope it will help you.

like image 174
Kishan Dhamat Avatar answered Sep 20 '25 14:09

Kishan Dhamat


Let us say that I have table named "persons" with some data

id | name | lastname

1 | john | Doe

2 | jane | Smith

and this is my simple code:

public String getRecords(String selectQuery){
    String recordSet = null;
    Cursor mCursor = database.rawQuery(selectQuery, null); 
    String[] colName = mCursor.getColumnNames();
   if (mCursor != null) {  

      recordSet = "{";
      mCursor.moveToFirst();

      do{
          StringBuilder sb = new StringBuilder();
          int columnsQty = mCursor.getColumnCount();
          for(int idx=0; idx<columnsQty; ++idx){
              sb.append(mCursor.getString(idx));
              if(idx<columnsQty-1){
                  sb.append(";");
              }
          }
          if(mCursor.getPosition()>0){
              recordSet +=",";
          }

          String row = formatRecords(colName, sb.toString());
          recordSet+= "\""+mCursor.getPosition()+"\":["+row+"]";

      }while(mCursor.moveToNext());

      recordSet += "}";

      return recordSet;


   }    
}
public String formatRecords(String[] colname, String rowData){
    String formatedData = null;
    String[] data = rowData.split(";");
    int colCount = colname.length;
    if(rowData !=null){
        formatedData = "{";
        for(int col=0; col<colCount; col++){
            if(col>0){
                formatedData += ", ";
            }
            formatedData += "\""+colname[col]+"\":\""+data[col]+"\"";
        }
        formatedData += "}";
    }
    Log.i(tag, formatedData);
    return formatedData

Then I will use it as

String data = getRecords("SELECT * FROM persons");

the return will like:

{"0":[{"id":"1","name":"john","lastname":"Doe"}],"1":[{"id":"2","name":"jane","lastname":"Smith"}]}

Anyway I made the return type as String for general purpose. :) Thanks.

like image 41
wehpogi Avatar answered Sep 20 '25 15:09

wehpogi