json array from sqlite to server

654 views Asked by At

I have to create a json arrray from the sqlite db and sent that json array as json fromat to a server My code for converting sqlite to json is...

  public JSONArray getResults()
{

    String myPath = "/data/data/com.example.sebastian.patientdetails/databases/MyDBName.db";// Set path to your database

    String myTable = TABLE_NAME;//Set name of your table



    SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    String searchQuery = "SELECT  * FROM " + myTable;
    Cursor cursor = myDataBase.rawQuery(searchQuery, null );

    JSONArray resultSet     = new JSONArray();

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {

        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("Data", cursor.getString(i) );
                        rowObject.put(cursor.getColumnName(i) ,  cursor.getString(i) );
                    }
                    else
                    {
                        rowObject.put( cursor.getColumnName(i) ,  "" );
                    }
                }
                catch( Exception e )
                {
                    Log.d("Data", e.getMessage()  );
                }
            }
        }
        resultSet.put(rowObject);
        cursor.moveToNext();
    }
    cursor.close();
   Log.d("Data", resultSet.toString() );

    return resultSet;

}

How can i send this json array to server to hit as json format at the server side? How can i do it. Please help me...

2

There are 2 answers

0
sanket pahuja On

You can use JsonArray request with POST method using the Google Volley library

0
Bills On

You can also use OkHttp to send post data to server. Add compile 'com.squareup.okhttp3:okhttp:3.4.1' in your build.gradle in dependencies. And use below code

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json);
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

Full code here

Call post method with URL and your JSON to send on server.