Example usage for android.os AsyncTask get

List of usage examples for android.os AsyncTask get

Introduction

In this page you can find the example usage for android.os AsyncTask get.

Prototype

public final Result get() throws InterruptedException, ExecutionException 

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:org.sigimera.app.android.controller.PersistanceController.java

/**
 * // ww w .  ja  v  a 2  s . co m
 * @param _authToken
 * @return
 */
public UsersStats getUsersStats(String _authToken) {
    UsersStats stats = this.pershandler.getUsersStats();
    if ((null == stats && _authToken != null) || (stats != null && stats.getUsername() == null)) {
        AsyncTask<String, Void, JSONObject> crisesStatsHelper = new StatisticUsersHttpHelper()
                .execute(_authToken);
        try {
            Log.d("[CRISES CONTROLLER]", "Response from API: " + crisesStatsHelper.get());
            this.pershandler.addUsersStats(crisesStatsHelper.get());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        stats = this.pershandler.getUsersStats();
    }
    return stats;
}

From source file:org.sigimera.app.android.controller.PersistanceController.java

public void updateNearCrises(String _auth_token, int _page, Location _location) {
    if (_location != null && _auth_token != null) {
        try {/*from  www .  ja  va2 s .co m*/
            AsyncTask<String, Void, JSONArray> crisesHelper = new NearCrisesHttpHelper().execute(_auth_token,
                    _page + "", _location.getLatitude() + "", _location.getLongitude() + "");
            JSONArray retArray = null;
            retArray = crisesHelper.get();
            this.pershandler.updateNearCrises(retArray);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public Socket createSocket(InetAddress inaddr, int i) throws IOException {
    AsyncTask<Object, Void, Object> socketCreationTask = new AsyncTask<Object, Void, Object>() {
        @Override/*w ww  . j av  a 2  s  . co m*/
        protected Object doInBackground(Object... params) {
            Object ret;
            try {
                ret = factory.createSocket((InetAddress) params[0], (int) params[1]);
            } catch (Exception e) {
                Log.wtf("F6 :" + getClass().getName(), e);
                ret = e;
            }
            return ret;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we
    // add this one a livelock will occur
    ExecutorService socketCreationExecutor = Executors.newFixedThreadPool(1);
    socketCreationTask.executeOnExecutor(socketCreationExecutor, inaddr, i);
    Object returned;
    try {
        returned = socketCreationTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.wtf("F7 :" + getClass().getName(), e);
        throw new IOException("Failure intentionally provoked. See log above.");
    }

    if (returned instanceof Exception) {
        throw (IOException) returned;
    } else {
        return (Socket) returned;
    }
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public Socket createSocket(String s, int i) throws IOException {
    AsyncTask<Object, Void, Object> socketCreationTask = new AsyncTask<Object, Void, Object>() {
        @Override/*from  w  ww. j av  a2s .c o  m*/
        protected Object doInBackground(Object... params) {
            Object ret;
            try {
                ret = factory.createSocket((String) params[0], (int) params[1]);
            } catch (Exception e) {
                Log.wtf("F10 :" + getClass().getName(), e);
                launchBroadcastChatEvent();
                ret = e;
            }
            return ret;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we
    // add this one a livelock will occur
    ExecutorService socketCreationExecutor = Executors.newFixedThreadPool(1);
    socketCreationTask.executeOnExecutor(socketCreationExecutor, s, i);
    Object returned;
    try {
        returned = socketCreationTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.wtf("F11 :" + getClass().getName(), e);
        throw new IOException("Failure intentionally provoked. See log above.");
    }

    if (returned instanceof Exception) {
        throw (IOException) returned;
    } else {
        return (Socket) returned;
    }
}

From source file:org.jorge.lolin1.io.net.HTTPServices.java

public static void downloadFile(final String whatToDownload, final File whereToSaveIt) throws IOException {
    logString("debug", "Downloading url " + whatToDownload);
    AsyncTask<Void, Void, Object> imageDownloadAsyncTask = new AsyncTask<Void, Void, Object>() {
        @Override//from   w w  w. j a v a  2s . c  o  m
        protected Object doInBackground(Void... params) {
            Object ret = null;
            BufferedInputStream bufferedInputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                logString("debug", "Opening stream for " + whatToDownload);
                bufferedInputStream = new BufferedInputStream(
                        new URL(URLDecoder.decode(whatToDownload, "UTF-8").replaceAll(" ", "%20"))
                                .openStream());
                logString("debug", "Opened stream for " + whatToDownload);
                fileOutputStream = new FileOutputStream(whereToSaveIt);

                final byte data[] = new byte[1024];
                int count;
                logString("debug", "Loop-writing " + whatToDownload);
                while ((count = bufferedInputStream.read(data, 0, 1024)) != -1) {
                    fileOutputStream.write(data, 0, count);
                }
                logString("debug", "Loop-written " + whatToDownload);
            } catch (IOException e) {
                return e;
            } finally {
                if (bufferedInputStream != null) {
                    try {
                        bufferedInputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
            }
            return ret;
        }
    };
    imageDownloadAsyncTask.executeOnExecutor(fileDownloadExecutor);
    Object returned = null;
    try {
        returned = imageDownloadAsyncTask.get();
    } catch (ExecutionException | InterruptedException e) {
        Crashlytics.logException(e);
    }
    if (returned != null) {
        throw (IOException) returned;
    }
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public Socket createSocket(String s, int i, InetAddress inaddr, int j) throws IOException {
    AsyncTask<Object, Void, Object> socketCreationTask = new AsyncTask<Object, Void, Object>() {
        @Override/* w ww . ja va  2 s .co m*/
        protected Object doInBackground(Object... params) {
            Object ret;
            try {
                ret = factory.createSocket((String) params[0], (int) params[1], (InetAddress) params[2],
                        (int) params[3]);
            } catch (Exception e) {
                Log.wtf("F8 :" + getClass().getName(), e);
                ret = e;
            }
            return ret;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we
    // add this one a livelock will occur
    ExecutorService socketCreationExecutor = Executors.newFixedThreadPool(1);
    socketCreationTask.executeOnExecutor(socketCreationExecutor, s, i, inaddr, j);
    Object returned;
    try {
        returned = socketCreationTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.wtf("F9 :" + getClass().getName(), e);
        throw new IOException("Failure intentionally provoked. See log above.");
    }

    if (returned instanceof Exception) {
        throw (IOException) returned;
    } else {
        return (Socket) returned;
    }
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public Socket createSocket(Socket socket, String s, int i, boolean flag) throws IOException {
    AsyncTask<Object, Void, Object> socketCreationTask = new AsyncTask<Object, Void, Object>() {
        @Override/*from  www  .j  a  va 2  s.co m*/
        protected Object doInBackground(Object... params) {
            Object ret;
            try {
                ret = factory.createSocket((Socket) params[0], (String) params[1], (int) params[2],
                        (boolean) params[3]);
            } catch (Exception e) {
                Log.wtf("F2 :" + getClass().getName(), e);
                ret = e;
            }
            return ret;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we
    // add this one a livelock will occur
    ExecutorService socketCreationExecutor = Executors.newFixedThreadPool(1);
    socketCreationTask.executeOnExecutor(socketCreationExecutor, socket, s, i, flag);
    Object returned;
    try {
        returned = socketCreationTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.wtf("F3 :" + getClass().getName(), e);
        throw new IOException("Failure intentionally provoked. See log above.");
    }

    if (returned instanceof Exception) {
        throw (IOException) returned;
    } else {
        return (Socket) returned;
    }
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public Socket createSocket(InetAddress inaddr, int i, InetAddress inaddr2, int j) throws IOException {
    AsyncTask<Object, Void, Object> socketCreationTask = new AsyncTask<Object, Void, Object>() {
        @Override//from ww  w.j  a  va2  s . c o  m
        protected Object doInBackground(Object... params) {
            Object ret;
            try {
                ret = factory.createSocket((InetAddress) params[0], (int) params[1], (InetAddress) params[2],
                        (int) params[3]);
            } catch (Exception e) {
                Log.wtf("F4 :" + getClass().getName(), e);
                ret = e;
            }
            return ret;
        }
    };
    //It's necessary to run the task in an executor because the main one is already full and if we
    // add this one a livelock will occur
    ExecutorService socketCreationExecutor = Executors.newFixedThreadPool(1);
    socketCreationTask.executeOnExecutor(socketCreationExecutor, inaddr, i, inaddr2, j);
    Object returned;
    try {
        returned = socketCreationTask.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.wtf("F5 :" + getClass().getName(), e);
        throw new IOException("Failure intentionally provoked. See log above.");
    }

    if (returned instanceof Exception) {
        throw (IOException) returned;
    } else {
        return (Socket) returned;
    }
}

From source file:com.windigo.RestApiMethodMetadata.java

/**
 * Make requests asyncronously with {@link AsyncTask} and return {@link HttpResponse}
 *
 * @param url//from  w w w.  ja va2  s. c  o  m
 * @param parameters
 * @return {@link HttpResponse}
 * @throws InterruptedException
 * @throws ExecutionException
 */
public Object makeAsyncRequest(final Request request)
        throws IOException, InterruptedException, ExecutionException {

    AsyncTask<Void, Integer, Object> backgroundTask = new AsyncTask<Void, Integer, Object>() {
        Response response;
        Object typedResponseObject;

        @Override
        protected Object doInBackground(Void... params) {
            try {
                response = httpClient.execute(request);

                if (response != null) {
                    response.setContentParser(typeParser);
                    typedResponseObject = typeParser.parse(response.getContentStream());
                    Logger.log("[Response] Typed response object: " + typedResponseObject.toString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JsonConversionException e) {
                e.printStackTrace();
            }
            return typedResponseObject;
        }

    }.execute();

    return backgroundTask.get();
}

From source file:org.labcrypto.wideroid.helpers.DownloadHelper.java

public byte[] downloadAsByteArray(final String url) throws IOException {
    try {//from   w  ww . j  a v a  2  s . co  m
        AsyncTask<Void, Void, byte[]> asyncTask = new AsyncTask<Void, Void, byte[]>() {
            @Override
            protected byte[] doInBackground(Void... params) {
                HttpGet httpGet = null;
                try {
                    HttpClient httpClient = AndroidHttpClient.newInstance("");
                    httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() != 200) {
                        return null;
                    }
                    return EntityUtils.toByteArray(httpResponse.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    try {
                        if (httpGet != null) {
                            httpGet.abort();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        };
        asyncTask.execute(new Void[] {});
        return asyncTask.get();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}