AsyncTask发布Json数组Android

时间:2016-11-18 09:46:20

标签: android json android-asynctask

我的Asynctask代码..

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

    }

}

我将json发送到服务器的代码..

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

如何使用Async任务返回json以将其发布到服务器。如何解决此问题。上述代码在execte()下的帖子代码中显示错误。 我该如何解决这个问题。?

1 个答案:

答案 0 :(得分:0)

而不是将TestAsync.execute()传递给AsyncTask而不是JsonArrayRequest。使用onPostExecute将数据传递给从doInBackground返回的服务器:

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

如果TestAsync是单独的类,则使用interface创建custom listener,以便在活动中从onPostExecute发送数据。