Android: Upload images to the server asynchronously

1

I'm sending a JSON of images with some data, my question is how I have to do to send the images asincron, so I do not have to wait for all the images to load so they can be sent but they are finished to upload that they are sent.

@Override
protected Void doInBackground(Object... params) {//ejecuta nuestras tareas principales
    CloseableHttpClient httpClient;
    CloseableHttpResponse httpResponse;

    try {
        CheckIn checkIn = CheckIn.getInstance();//hago una instancia de checkin
        JSONObject jsonObject = new JSONObject();//creo un JSONObject

        ArrayList<Bitmap> listOfBitmaps = (ArrayList<Bitmap>) params[0];//Obtengo mi Arreglo de objetos para despues pasarlos a un array lis de Bitmap
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();//permitira la salida de los bytes

        ArrayList<String> listOfStrings = new ArrayList<String>();//creo un arrayLIsto de String

        for (int i = 0; i < listOfBitmaps.size(); i++){//itero el arreglo
            listOfBitmaps.get(i).compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);//se comprime la imagen
            byte[] byteArray = byteArrayOutputStream .toByteArray();//codifica el path a un arreglo de byte
            String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);//codifico ese byteArray a base64 y despues a scrintg

            listOfStrings.add(encoded);//agrego al arreglo de strings
        }
        jsonObject.put("folio", checkIn.getFolio());//paso el folio al JSONObject
        jsonObject.put("images", listOfStrings);//le paso al JSONObject los codigos de las iameges
        StringEntityHC4 entityHC4 = new StringEntityHC4(jsonObject.toString(), ContentType.create("json/application", "UTF-8"));//la direccion del servidor a la que va a apuntar
        HttpPutHC4 httpPutHC4 = new HttpPutHC4(DynamicUrl.BASE_URL+DynamicUrl.SERVER_HOST+":"+DynamicUrl.SERVER_PORT+"/api/checkkin");//la direccion del dervidor al que va a apuntar
        httpPutHC4.setEntity(entityHC4);//seteo los datos que tengo en el JSONObject
        httpClient = HttpClients.createDefault();//La configuracion del servidor va a ser default
        httpResponse = httpClient.execute(httpPutHC4);//Obtengo la respuesta del servidor

        if (httpResponse.getStatusLine().getStatusCode() == 200) {//si el estatus de la respuesta es igual a 200
            JSONObject jsonRosponse = new JSONObject(EntityUtilsHC4.toString(httpResponse.getEntity()));//creo un JSONObject y le paso el JSON que recibio de la sespuesta del servidor

            if (jsonRosponse.getString("code").equals("OK")) {//checo que el JSON tenga la clave OK
                System.out.println("Las imagenes se guardaron correctamente");
            } else {
                System.out.println("Error al subir las imagenes");
            }
        } else {
            System.out.println("Ocurrio un error");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
    
asked by Javier fr 12.12.2016 в 18:35
source

1 answer

3

You just need to change all of your image fix processing to the for and send 1 by 1

for (int i = 0; i < listOfBitmaps.size(); i++) { //itero el arreglo
        listOfBitmaps.get(i).compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream); //se comprime la imagen
        byte[] byteArray = byteArrayOutputStream.toByteArray(); //codifica el path a un arreglo de byte
        String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT); //codifico ese byteArray a base64 y despues a scrintg
        jsonObject.put("folio", checkIn.getFolio()); //paso el folio al JSONObject
        jsonObject.put("imagen", encoded); //le paso al JSONObject los codigos de las iameges
        StringEntityHC4 entityHC4 = new StringEntityHC4(jsonObject.toString(), ContentType.create("json/application", "UTF-8")); //la direccion del servidor a la que va a apuntar
        HttpPutHC4 httpPutHC4 = new HttpPutHC4(DynamicUrl.BASE_URL + DynamicUrl.SERVER_HOST + ":" + DynamicUrl.SERVER_PORT + "/api/checkkin"); //la direccion del dervidor al que va a apuntar
        httpPutHC4.setEntity(entityHC4); //seteo los datos que tengo en el JSONObject
        httpClient = HttpClients.createDefault(); //La configuracion del servidor va a ser default
        httpResponse = httpClient.execute(httpPutHC4); //Obtengo la respuesta del servidor

        if (httpResponse.getStatusLine().getStatusCode() == 200) { //si el estatus de la respuesta es igual a 200
            JSONObject jsonRosponse = new JSONObject(EntityUtilsHC4.toString(httpResponse.getEntity())); //creo un JSONObject y le paso el JSON que recibio de la sespuesta del servidor

            if (jsonRosponse.getString("code").equals("OK")) { //checo que el JSON tenga la clave OK
                System.out.println("La imagen se guardo correctamente");
            } else {
                System.out.println("Error al subir la imagen");
            }
        } else {
            System.out.println("Ocurrio un error");
        }
    }

You no longer send an array in jsonObject.put("images", listOfStrings); , otherwise you send jsonObject.put("imagen", encoded); and each iteration of the for is an upload to the server.

EDITING

Regarding your question How do I give an image URL to an ImageView?

public class ImageLoadTask extends AsyncTask < Void, Void, Bitmap > {

    private String url;
    private ImageView imageView;

    public ImageLoadTask(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(Void...params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
                .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        imageView.setImageBitmap(result);
    }
}

You can call it new ImageLoadTask(url, imageView).execute();

I recommend you do it also in an asynchronous task, since as you are simulating load of images and are from the internet, some may fail, if this fails it will not affect your application, but anyway this code would be simple without an asynchronous task.

public static Bitmap getBitmapFromURL(String url_image) {
    try {
        URL url = new URL(url_image);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap","returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
        return null;
    }
}

This is a reference of the question in StackOverFlow English

    
answered by 12.12.2016 в 20:15