0

I have an upload(String base_code) method that takes a file in form of base64 encoded string, this method makes a post request with the base64 string to an api endpoint to upload the file in the server, and if the upload is successful, the api endpoint will return a 200 status code.

 public static void upload(final String base_code) {

    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try  {

                Request request;
                RequestBody request_body;
                Response response;
                MultipartBody.Builder body = new MultipartBody.Builder();

                body.setType(MultipartBody.FORM);
                body.addFormDataPart("img", base_code);

                request_body = body.build();
                request = new Request.Builder().url("https://api/endpoint/upload").post(request_body).build();
                response = client.newCall(request).execute();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

}

I would like for the method upload() to return a true or false whether the upload is successful, however I can't do that since the code executes in a its own thread. How would I do this?

The post request is done via the okhttp3 lib and I can determine whether the upload was successful by checking response.code().

Thanks

tosi
  • 611
  • 9
  • 24

2 Answers2

0

Use AsyncTask. You can execute the thread in doInBackground method and pass the data back to the uiThread via onPostExecute method.

Check this out.

Shivam Kumar
  • 1,892
  • 2
  • 21
  • 33
user456
  • 262
  • 2
  • 9
0

I prefer use ExecutorService or AsyncTask. Use thread immediately is hard to manage.

Use ExecutorService to monitor the status of task:

ExecutorService es = Executors.newCachedThreadPool();
Future future = es.submit(new Runnable() {
    @Override
    public void run() {
       // Http post here
    }
});

Then you can call method of Future to check the execute status.

Use AsyncTask:

private class postTask extends AsyncTask<String, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(String... strings) {
        // Http post here
        return result == 200;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        // Do something according to `success`
    }
}

Then call execute(url) or executeOnExecutor(es, url) to start;

Neo Shen
  • 110
  • 2
  • 11