Example usage for android.os AsyncTask AsyncTask

List of usage examples for android.os AsyncTask AsyncTask

Introduction

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

Prototype

public AsyncTask() 

Source Link

Document

Creates a new asynchronous task.

Usage

From source file:mc.lib.network.AsyncNetworkHelper.java

public static void getAsText(final String url, final String encoding,
        final OnCompleteListener<String> listener) {
    new AsyncTask<Void, Void, String>() {
        @Override//from   ww w  . j  a  v  a2s  .  c o  m
        protected String doInBackground(Void... params) {
            return NetworkHelper.getAsText(url, encoding);
        }

        @Override
        protected void onPostExecute(String res) {
            super.onPostExecute(res);
            listener.complete(res);
        }
    }.execute((Void) null);
}

From source file:com.aleiacampo.oristanobus.util.ViewUtil.java

public static void loadMostSearched(final AppCompatActivity appCompatActivity) {

    final ArrayList<Stop> stopsList = new ArrayList<>();
    final ArrayList<String> stopsNameList = new ArrayList<>();

    new AsyncTask<Void, Void, Void>() {

        @Override// w  ww  . j  a v a  2  s .co  m
        protected void onPreExecute() {
            super.onPreExecute();
            if (!ConnectionsHandler.isNetworkPresent(appCompatActivity)) {
                this.cancel(true);
                stopsNameList.add("Connessione dati non presente");
                ListView listView_searched = (ListView) appCompatActivity
                        .findViewById(R.id.textView_mostSerched);
                ArrayAdapter<String> adapter = new ArrayAdapter<>(appCompatActivity.getApplicationContext(),
                        R.layout.text_view, stopsNameList);
                listView_searched.setAdapter(adapter);
            }
        }

        @Override
        protected Void doInBackground(Void... params) {

            Stop stop;
            String url = "http://www.aleiacampo.com/stops.php?clicked=10";
            WebServerHandler webServerHandler = new WebServerHandler();
            String jsonStr = webServerHandler.getJSONData(url);
            try {
                JSONObject jsonObject = new JSONObject(jsonStr);
                JSONArray stopsJSON = jsonObject.getJSONArray("bus_stops");
                for (int i = 0; i < stopsJSON.length(); i++) {
                    JSONObject bus_stop = stopsJSON.getJSONObject(i);
                    stop = new Stop(bus_stop.getInt("id_line"), bus_stop.getInt("id_stop"),
                            bus_stop.getString("name_line"), bus_stop.getString("name_stop"));
                    stopsList.add(stop);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

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

            for (Stop stop : stopsList) {
                stopsNameList.add("Linea " + stop.idLine + " - " + stop.nameStop);
            }

            ListView listView_searched = (ListView) appCompatActivity.findViewById(R.id.textView_mostSerched);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(appCompatActivity.getApplicationContext(),
                    R.layout.text_view, stopsNameList);
            listView_searched.setAdapter(adapter);
            listView_searched.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    Bundle bundle = new Bundle();
                    bundle.putInt("id_stop", stopsList.get(position).idStop);
                    bundle.putInt("id_line", stopsList.get(position).idLine);
                    bundle.putString("name_line", stopsList.get(position).nameLine);
                    bundle.putString("name_stop", stopsList.get(position).nameStop);

                    FragmentManager fragmentManager = appCompatActivity.getSupportFragmentManager();
                    TimesFragment timesFragment = new TimesFragment();
                    timesFragment.setArguments(bundle);
                    appCompatActivity.onBackPressed();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.replace(R.id.home_frag, timesFragment, "Times");
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();

                }
            });
        }
    }.execute();
}

From source file:org.starfishrespect.myconsumption.android.tasks.SensorValuesUpdater.java

public void refreshDB() {

    AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() {
        @Override/*w w  w  .  j  a va  2 s.c o  m*/
        protected Void doInBackground(Void... params) {
            DatabaseHelper db = SingleInstance.getDatabaseHelper();
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<List> responseEnt;
            template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

            try {
                SensorValuesDao valuesDao = new SensorValuesDao(db);
                for (SensorData sensor : db.getSensorDao().queryForAll()) {
                    int startTime = (int) (sensor.getLastLocalValue().getTime() / 1000);
                    String url = String.format(SingleInstance.getServerUrl() + "sensors/%s/data?start=%d",
                            sensor.getSensorId(), startTime);
                    Log.d(TAG, url);
                    responseEnt = template.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders),
                            List.class);
                    List<List<Integer>> sensorData = responseEnt.getBody();
                    List<SensorValue> values = new ArrayList<>();
                    long last = 0;
                    long first = Long.MAX_VALUE;
                    for (List<Integer> value : sensorData) {
                        values.add(new SensorValue(value.get(0), value.get(1)));
                        if (value.get(0) > last) {
                            last = value.get(0);
                        }
                        if (value.get(0) < first) {
                            first = value.get(0);
                        }
                    }
                    valuesDao.insertSensorValues(sensor.getSensorId(), values);
                    sensor.setLastLocalValue(new Date(last * 1000));
                    long formerFirst = sensor.getFirstLocalValue().getTime() / 1000;
                    if (formerFirst > first || formerFirst == 0) {
                        sensor.setFirstLocalValue(new Date(first * 1000));
                    }
                    db.getSensorDao().update(sensor);
                    Log.d(TAG, "Inserted values to " + last);
                }
            } catch (SQLException e) {
                Log.e(TAG, "Error:" + e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (updateFinishedCallback != null) {
                updateFinishedCallback.onUpdateFinished();
            }
        }
    };

    task.execute();
}

From source file:org.starfishrespect.myconsumption.android.tasks.ConfigUpdater.java

public void refreshDB() {

    AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() {
        @Override/*from   w w  w.  j  a  v  a  2 s .c om*/
        protected Void doInBackground(Void... params) {
            DatabaseHelper db = SingleInstance.getDatabaseHelper();
            RestTemplate template = new RestTemplate();
            template.getMessageConverters().add(new MappingJacksonHttpMessageConverter());

            try {
                String url = SingleInstance.getServerUrl() + "configs/co2";
                Double co2 = template.getForObject(url, Double.class);

                int id = db.getIdForKey("config_co2");
                KeyValueData valueData = new KeyValueData("config_co2", co2.toString());
                valueData.setId(id);

                LOGD(TAG, "writing stat in local db: " + co2);
                db.getKeyValueDao().createOrUpdate(valueData);

            } catch (SQLException e) {
                LOGD(TAG, "Cannot create config co2", e);
            } catch (ResourceAccessException | HttpClientErrorException e) {
                LOGE(TAG, "Cannot access server ", e);
            }

            try {
                String url = SingleInstance.getServerUrl() + "configs/day";
                Double day = template.getForObject(url, Double.class);

                int id = db.getIdForKey("config_day");
                KeyValueData valueData = new KeyValueData("config_day", day.toString());
                valueData.setId(id);

                LOGD(TAG, "writing stat in local db: " + day);
                db.getKeyValueDao().createOrUpdate(valueData);

            } catch (SQLException e) {
                LOGD(TAG, "Cannot create config day", e);
            } catch (ResourceAccessException | HttpClientErrorException e) {
                LOGE(TAG, "Cannot access server ", e);
            }

            try {
                String url = SingleInstance.getServerUrl() + "configs/night";
                Double night = template.getForObject(url, Double.class);

                int id = db.getIdForKey("config_night");
                KeyValueData valueData = new KeyValueData("config_night", night.toString());
                valueData.setId(id);

                LOGD(TAG, "writing stat in local db: " + night);
                db.getKeyValueDao().createOrUpdate(valueData);

            } catch (SQLException e) {
                LOGD(TAG, "Cannot create config night", e);
            } catch (ResourceAccessException | HttpClientErrorException e) {
                LOGE(TAG, "Cannot access server ", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (configUpdateFinishedCallback != null) {
                configUpdateFinishedCallback.onConfigUpdateFinished();
            }
        }
    };

    task.execute();
}

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

public byte[] downloadAsByteArray(final String url) throws IOException {
    try {/*  w w  w .j a  v a 2  s .c  o  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);
    }
}

From source file:com.comcast.freeflow.examples.artbook.models.DribbbleFetch.java

public void load(final ArtbookActivity caller, int itemsPerPage, int page) {

    new AsyncTask<String, Void, String>() {

        OkHttpClient client = new OkHttpClient();

        private Exception exception;

        private Response makeUrlRequest(String url) throws IOException {
            Request.Builder request = new Request.Builder().url(url).header("Accept", "application/json");

            final Response response = client.newCall(request.build()).execute();
            return response;
        }//ww w.  j a v a  2  s. c  o m

        protected String doInBackground(String... urls) {
            try {
                String body;
                Response r = makeUrlRequest(urls[0]);
                int res_code = r.code();
                if (res_code == 200) {
                    body = r.body().string();
                    /**
                     I just solved the problem. It was somewhat misleading that the cache tests where failing when I tried to use OkHttp from source.
                     The problem was quite easy and it was that other of the request methods was getting a body on the response, and it wasn't closed at the end. That explains why I saw the ".tmp" file in the cache, but still a confusing and misleading because of the fact that this request method was consuming and closing the body from the response. Its like the lock or monitor for the cache editor is global for all requests, instead of being by request. I though it wasn't when I read the code, when it used a hash for the request as a key.
                     */
                    r.body().close();
                } else {
                    Log.d(TAG, "error code: " + res_code);
                    Log.d(TAG, "found error on curl: " + urls[0]);
                    throw new Exception("server error: " + res_code);
                }
                return body;
            } catch (Exception e) {
                this.exception = e;
                Log.e(TAG, "Exception: " + e);
                return null;
            }
        }

        protected void onPostExecute(String data) {
            DribbbleFeed feed = new Gson().fromJson(data, DribbbleFeed.class);
            caller.onDataLoaded(feed);
        }

    }.execute("http://api.dribbble.com/shots/popular?per_page=" + itemsPerPage + "&page=" + page);
}

From source file:org.starfishrespect.myconsumption.android.tasks.GCMRegister.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>/*  www  .j  a  v a2 s.c om*/
 * Stores the registration ID and app versionCode in the application's
 * shared preferences.
 */
public void registerInBackground(final Context context) {
    AsyncTask<Void, List, String> task = new AsyncTask<Void, List, String>() {
        @Override
        protected String doInBackground(Void... params) {
            RestTemplate template = new RestTemplate();
            HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser();
            ResponseEntity<String> responseEnt;
            template.getMessageConverters().add(new FormHttpMessageConverter());
            template.getMessageConverters().add(new StringHttpMessageConverter());
            String msg = "";

            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                String regid = gcm.register(Config.SENDER_ID);
                msg = "Device registered, registration ID=" + regid;

                // Send the registration ID to the server
                String url = SingleInstance.getServerUrl() + "notifs/"
                        + SingleInstance.getUserController().getUser().getName() + "/id/" + regid;

                responseEnt = template.exchange(url, HttpMethod.POST, new HttpEntity<>(httpHeaders),
                        String.class);
                SimpleResponseDTO response = new ObjectMapper().readValue(responseEnt.getBody(),
                        SimpleResponseDTO.class);

                if (response.getStatus() != SimpleResponseDTO.STATUS_SUCCESS) {
                    msg = "Error: " + response.getStatus() + " Cannot post register id on server side.";
                }

                // Persist the registration ID - no need to register again.
                PrefUtils.setRegistrationId(context, regid);
            } catch (IOException ex) {
                msg = "Error:" + ex.getMessage();
                // If there is an error, don't just keep trying to register.
                // Require the user to click a button again, or perform
                // exponential back-off.
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            LOGI(TAG, msg);
        }
    };

    task.execute();
}

From source file:com.example.carrie.carrie_test1.DrugListActivity.java

private void load_data_from_server(int id) {

    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override//from w w  w.ja  v  a 2 s  . com
        protected Void doInBackground(Integer... integers) {

            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("http://54.65.194.253/Drug/ShowDrug.php?id=" + integers[0]).build();
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());

                for (int i = 0; i < array.length(); i++) {

                    JSONObject object = array.getJSONObject(i);

                    Drug data = new Drug(object.getInt("id"), object.getString("chineseName"),
                            object.getString("licenseNumber"), object.getString("indication"),
                            object.getString("englishName"));

                    data_list.add(data);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                System.out.println("End of content");
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            adapter.notifyDataSetChanged();
        }
    };

    task.execute(id);
}

From source file:com.github.secondsun.catfactsdemo.networking.AsyncTaskbasedFactLoader.java

private AsyncTask<Void, Void, List<String>> makeTask() {
    return new AsyncTask<Void, Void, List<String>>() {
        @Override//from  ww w .j ava2  s .  co  m
        protected List<String> doInBackground(Void... params) {
            try {

                if (data != null && data.size() > 0) {
                    return data;
                }

                Thread.sleep(Constants.DELAY);

                OkHttpClient client = new OkHttpClient();

                Request request = new Request.Builder().url(Constants.CAT_FACTS_URL).build();

                Response response = client.newCall(request).execute();

                JSONObject responseJson = new JSONObject(response.body().string());
                JSONArray facts = responseJson.getJSONArray("facts");

                ArrayList<String> toReturn = new ArrayList<>(facts.length());

                for (int i = 0; i < facts.length(); i++) {
                    toReturn.add(facts.getString(i));
                }

                data = toReturn;

                return toReturn;

            } catch (InterruptedException | IOException | JSONException e) {
                ArrayList<String> toReturn = new ArrayList<>();
                toReturn.add("Error:" + e.getMessage());
                data = toReturn;
                return toReturn;
            }
        }

        @Override
        protected void onPostExecute(List<String> strings) {
            super.onPostExecute(strings);
            if (activity != null) {
                activity.displayFacts(strings);
            }
        }
    };

}

From source file:br.com.anteros.vendas.gui.SplashActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);/*  w ww . j a  v a2 s  . co m*/

    /**
     * IMPORTANTE: Atribui o contexto da aplicao que ser usado em vrios pontos
     * da aplicao.
     */
    AnterosVendasContext.setApplication(getApplication());
    AnterosVendasContext.getInstance();

    new AsyncTask<Void, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
                startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                finish();

                return Boolean.TRUE;

            } catch (Exception e) {
                e.printStackTrace();
            }
            return Boolean.FALSE;
        }
    }.execute();
}