-1

I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that I am calling asynctask as

new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();

and my asynctask function is as:

public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {

            String loginUserInfoId = "";
            String filePath = "";
            long totalSize = 0;
            public UploadFileToServer(String userInfoId, String url){
                loginUserInfoId = userInfoId;
                filePath = url;
            }

            @Override
            protected void onPreExecute() {
                // setting progress bar to zero
                super.onPreExecute();
            }

            @Override
            protected void onProgressUpdate(Integer... progress) {
                // Making progress bar visible

                // updating progress bar value
            }

            @Override
            protected String doInBackground(Void... params) {
                return uploadFile();
            }

            @SuppressWarnings("deprecation")
            private String uploadFile() {
                String responseString = null;

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(Config.HOST_NAME +     "/AndroidApp/AddMessageFile/"+loginUserInfoId);

                try {
                    AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                            new AndroidMultiPartEntity.ProgressListener() {

                                @Override
                                public void transferred(long num) {
                                    publishProgress((int) ((num / (float) totalSize) * 100));
                                }
                            });

                    File sourceFile = new File(filePath);

                    // Adding file data to http body
                    entity.addPart("file", new FileBody(sourceFile));

                    totalSize = entity.getContentLength();
                    httppost.setEntity(entity);

                    // Making server call
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity r_entity = response.getEntity();

                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode == 200) {
                        // Server response
                        responseString = EntityUtils.toString(r_entity);
                    } else {
                        responseString = "Error occurred! Http Status Code: "
                                + statusCode;
                    }

                } catch (ClientProtocolException e) {
                    responseString = e.toString();
                } catch (IOException e) {
                    responseString = e.toString();
                }
                responseString = responseString.replace("\"","");
                return responseString;

            }

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

        }
jh314
  • 27,144
  • 16
  • 62
  • 82
Neeraj Mehta
  • 1,675
  • 2
  • 22
  • 45

2 Answers2

0

Try my code as given below.

public Result CallServer(String params)
{
try
{
    MainAynscTask task = new MainAynscTask();
    task.execute(params);
    Result aResultM = task.get();  //Add this
}
catch(Exception ex)
{
     ex.printStackTrace();
}
 return aResultM;//Need to get back the result

}

Samir Bhatt
  • 3,041
  • 2
  • 25
  • 39
0

You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:

public interface MyListener {
    void onDataArrived(String data);
}

And inject an instance implementing it at the AsyncTask constructor:

public UploadFileToServer(String userInfoId, String url, MyListener listener){
    loginUserInfoId = userInfoId;
    filePath = url;
    mListener = listener;
}

Now, you can simply use it at the onPostExecute:

@Override
protected void onPostExecute(String result) {
    listener.onDataArrived(result);
    super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}

If you are looking for a more complex solutions, you can start from reading this article.

nikis
  • 11,166
  • 2
  • 35
  • 45