Tom Tom - 17 days ago 20
Android Question

AsyncTask to Post Json array Android

My Asynctask code..

private class TestAsync extends AsyncTask<Object, Object, JSONArray> {

@Override
protected void onPreExecute() {
super.onPreExecute();


}

@Override
protected JSONArray doInBackground(Object... arg0) {

Cursor cursor = mydb.getDat();

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) );

Bitmap bitmap = BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(DBHelper.PHOTO)));
// Log.d("pic",bitmap.toString());
String en= encodeToBase64(bitmap, Bitmap.CompressFormat.JPEG,10);

// Log.d("dn",en);

rowObject.put("pic",en);





}
else
{



rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
// Log.d("Data", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("Final Json", resultSet.toString() );

return resultSet;


}

@Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);

}

}


My code to send json to server..

JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
server_url, new TestAsync.execute(),
new Response.Listener<JSONArray>() {


How can i use Async task to return json to post it to the server.How can i resolve this issue.The above code shows error in the post code under
execte()
.
How can i resolve this issue.?

Answer

Instead of passing TestAsync.execute() which return AsyncTask to JsonArrayRequest. use onPostExecute for passing data to sever returned from doInBackground :

@Override
protected void onPostExecute(JSONArray result) {
    super.onPostExecute(result);
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST,
                server_url,result,
                new Response.Listener<JSONArray>() {
}

If TestAsync is separate class then create custom listener using interface for sending data from onPostExecute in Activity.

Comments