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:com.naman14.algovisualizer.AlgoDescriptionFragment.java

public void setCodeDesc(final String key) {
    if (descJson == null && getActivity() != null) {
        new AsyncTask<Void, String, String>() {
            @Override/*from   www.  j  ava2 s.  c  o  m*/
            protected String doInBackground(Void... params) {
                return DataUtils.readDescJson(getActivity());
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                descJson = s;
                try {
                    descObject = new JSONObject(descJson);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                addDescData(key);
            }
        }.execute();
    } else
        addDescData(key);
}

From source file:com.finalproject.deliveronthego.SignUpDriver.java

public void getRegId() {
    new AsyncTask<Void, Void, String>() {
        @Override/*from w  w  w.  j  a va2s  . c  o m*/
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                regid = gcm.register(projectNumber);
                msg = "Device registered, registration ID=" + regid;
                Log.i("GCM", msg);

            } catch (IOException ex) {
                msg = "Error :" + ex.getMessage();

            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            Log.v("reg id", msg);
            new MyDriverSignup(getBaseContext()).execute(firstName.getText().toString(),
                    lastName.getText().toString(), password.getText().toString(),
                    driverLicense.getText().toString(), emailid.getText().toString(),
                    phoneNumber.getText().toString(), msg);

        }
    }.execute(null, null, null);
}

From source file:com.github.dfa.diaspora_android.task.GetPodsService.java

private void getPods() {
    /*/*  w w w.  j  a  v  a  2 s .c  om*/
     * Most of the code in this AsyncTask is from the file getPodlistTask.java
     * from the app "Diaspora Webclient".
     * A few modifications and adaptations were made by me.
     * Source:
     * https://github.com/voidcode/Diaspora-Webclient/blob/master/src/com/voidcode/diasporawebclient/getPodlistTask.java
     * Thanks to Terkel Srensen ; License : GPLv3
     */
    AsyncTask<Void, Void, String[]> getPodsAsync = new AsyncTask<Void, Void, String[]>() {
        @Override
        protected String[] doInBackground(Void... params) {

            // TODO: Update deprecated code

            StringBuilder builder = new StringBuilder();
            //HttpClient client = new DefaultHttpClient();
            List<String> list = null;
            HttpsURLConnection connection;
            InputStream inStream;
            try {
                connection = NetCipher
                        .getHttpsURLConnection("https://podupti.me/api.php?key=4r45tg&format=json");
                int statusCode = connection.getResponseCode();
                if (statusCode == 200) {
                    inStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }

                    try {
                        inStream.close();
                    } catch (IOException e) {
                        /*Nothing to do*/}

                    connection.disconnect();
                } else {
                    AppLog.e(this, "Failed to download list of pods");
                }
            } catch (IOException e) {
                //TODO handle json buggy feed
                e.printStackTrace();
            }
            //Parse the JSON Data
            try {
                JSONObject jsonObjectAll = new JSONObject(builder.toString());
                JSONArray jsonArrayAll = jsonObjectAll.getJSONArray("pods");
                AppLog.d(this, "Number of entries " + jsonArrayAll.length());
                list = new ArrayList<>();
                for (int i = 0; i < jsonArrayAll.length(); i++) {
                    JSONObject jo = jsonArrayAll.getJSONObject(i);
                    if (jo.getString("secure").equals("true"))
                        list.add(jo.getString("domain"));
                }

            } catch (Exception e) {
                //TODO Handle Parsing errors here
                e.printStackTrace();
            }
            if (list != null)
                return list.toArray(new String[list.size()]);
            else
                return null;
        }

        @Override
        protected void onPostExecute(String[] pods) {
            Intent broadcastIntent = new Intent(MESSAGE_PODS_RECEIVED);
            broadcastIntent.putExtra("pods", pods != null ? pods : new String[0]);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
            stopSelf();
        }
    };
    getPodsAsync.execute();
}

From source file:com.networksaremadeofstring.anonionooid.RelayGraphDetailsFragment.java

@Override
public void onResume() {
    super.onResume();
    try {/*from  w w  w  .  j  a  v  a2s .co m*/
        graphContainer.removeAllViews();
    } catch (Exception e) {
        e.printStackTrace();
    }

    new AsyncTask<Void, Void, JSONObject>() {
        @Override
        protected JSONObject doInBackground(Void... params) {
            try {
                return API.getRelayGraphs(getArguments().getString(Ooo.ARG_ITEM_ID));
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(JSONObject graphDetails) {
            //3 Day View
            try {
                int writeValueCount = graphDetails.getJSONObject("write_history").getJSONObject("3_days")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] writeValues = new GraphView.GraphViewData[writeValueCount];
                for (int i = 0; i < writeValueCount; i++) {
                    writeValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("write_history")
                            .getJSONObject("3_days").getJSONArray("values").getInt(i));
                }
                GraphViewSeries writeSeries = new GraphViewSeries("Write Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(31, 119, 180), 1), writeValues);

                int readValueCount = graphDetails.getJSONObject("read_history").getJSONObject("3_days")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] readValues = new GraphView.GraphViewData[readValueCount];
                for (int i = 0; i < readValueCount; i++) {
                    readValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("read_history")
                            .getJSONObject("3_days").getJSONArray("values").getInt(i));
                }
                GraphViewSeries readSeries = new GraphViewSeries("Read Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(255, 127, 14), 1), readValues);

                GraphView graphView = new LineGraphView(getActivity(), "3 Day Bandwidth Activity");
                graphView.addSeries(writeSeries);
                graphView.addSeries(readSeries);
                graphView.setMinimumHeight(400);
                graphView.setMinimumWidth(200);
                graphView.setShowLegend(true);
                graphView.setScalable(true);
                graphView.setHorizontalLabels(new String[] {
                        graphDetails.getJSONObject("read_history").getJSONObject("3_days").getString("first"),
                        graphDetails.getJSONObject("read_history").getJSONObject("3_days").getString("last") });
                graphContainer.addView(graphView);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //1 week View
            try {
                int writeValueCount = graphDetails.getJSONObject("write_history").getJSONObject("1_week")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] writeValues = new GraphView.GraphViewData[writeValueCount];
                for (int i = 0; i < writeValueCount; i++) {
                    writeValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("write_history")
                            .getJSONObject("1_week").getJSONArray("values").getInt(i));
                }
                GraphViewSeries writeSeries = new GraphViewSeries("Write Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(31, 119, 180), 1), writeValues);

                int readValueCount = graphDetails.getJSONObject("read_history").getJSONObject("1_week")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] readValues = new GraphView.GraphViewData[readValueCount];
                for (int i = 0; i < readValueCount; i++) {
                    readValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("read_history")
                            .getJSONObject("1_week").getJSONArray("values").getInt(i));
                }
                GraphViewSeries readSeries = new GraphViewSeries("Read Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(255, 127, 14), 1), readValues);

                GraphView graphView = new LineGraphView(getActivity(), "1 Week Bandwidth Activity");
                graphView.addSeries(writeSeries);
                graphView.addSeries(readSeries);
                graphView.setMinimumHeight(400);
                graphView.setMinimumWidth(200);
                graphView.setShowLegend(true);
                graphView.setHorizontalLabels(new String[] {
                        graphDetails.getJSONObject("read_history").getJSONObject("1_week").getString("first"),
                        graphDetails.getJSONObject("read_history").getJSONObject("1_week").getString("last") });
                graphView.setScalable(true);

                graphContainer.addView(graphView);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //1 Month View
            try {
                int writeValueCount = graphDetails.getJSONObject("write_history").getJSONObject("1_month")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] writeValues = new GraphView.GraphViewData[writeValueCount];
                for (int i = 0; i < writeValueCount; i++) {
                    writeValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("write_history")
                            .getJSONObject("1_month").getJSONArray("values").getInt(i));
                }
                GraphViewSeries writeSeries = new GraphViewSeries("Write Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(31, 119, 180), 1), writeValues);

                int readValueCount = graphDetails.getJSONObject("read_history").getJSONObject("1_month")
                        .getJSONArray("values").length();
                GraphView.GraphViewData[] readValues = new GraphView.GraphViewData[readValueCount];
                for (int i = 0; i < readValueCount; i++) {
                    readValues[i] = new GraphView.GraphViewData(i, graphDetails.getJSONObject("read_history")
                            .getJSONObject("1_month").getJSONArray("values").getInt(i));
                }
                GraphViewSeries readSeries = new GraphViewSeries("Read Rate",
                        new GraphViewSeries.GraphViewSeriesStyle(Color.rgb(255, 127, 14), 1), readValues);

                GraphView graphView = new LineGraphView(getActivity(), "1 Month Bandwidth Activity");
                graphView.addSeries(writeSeries);
                graphView.addSeries(readSeries);
                graphView.setMinimumHeight(400);
                graphView.setMinimumWidth(200);
                graphView.setShowLegend(true);
                graphView.setScalable(true);
                graphView.setHorizontalLabels(new String[] {
                        graphDetails.getJSONObject("read_history").getJSONObject("1_month").getString("first"),
                        graphDetails.getJSONObject("read_history").getJSONObject("1_month")
                                .getString("last") });
                graphContainer.addView(graphView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.execute(null, null, null);
}

From source file:bf.io.openshop.ux.dialogs.LicensesDialogFragment.java

/**
 * Load file with licenses. Using AsyncTask just in case of a big file.
 *//*from w  ww .  j a va2 s  . c  o m*/
private void loadLicenses() {
    licenseAsyncTask = new AsyncTask<Void, Void, String>() {

        @Override
        protected String doInBackground(Void... params) {
            InputStream rawResource = getActivity().getResources().openRawResource(R.raw.licenses);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(rawResource));

            String line;
            StringBuilder sb = new StringBuilder();

            try {
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line);
                    sb.append("\n");
                }
                bufferedReader.close();
            } catch (IOException e) {
                Timber.e(e, "Load licenses failed.");
            }
            return sb.toString();
        }

        @Override
        protected void onPostExecute(String licensesBody) {
            super.onPostExecute(licensesBody);
            if (getActivity() == null || isCancelled()) {
                return;
            }
            progressBar.setVisibility(View.INVISIBLE);
            licenseWebView.setVisibility(View.VISIBLE);
            licenseWebView.loadDataWithBaseURL(null, licensesBody, "text/html", "utf-8", null);
            licenseAsyncTask = null;
        }
    }.execute();
}

From source file:com.codebutler.farebot.activities.ReadingTagActivity.java

private void resolveIntent(Intent intent) {
    final TextView textView = (TextView) findViewById(R.id.textView);

    try {/*from   ww  w  . j ava 2  s . co  m*/
        Bundle extras = intent.getExtras();

        final Tag tag = (Tag) extras.getParcelable("android.nfc.extra.TAG");
        ;
        final String[] techs = tag.getTechList();

        new AsyncTask<Void, String, MifareCard>() {
            Exception mException;

            @Override
            protected MifareCard doInBackground(Void... params) {
                try {
                    if (ArrayUtils.contains(techs, "android.nfc.tech.NfcB"))
                        return CEPASCard.dumpTag(tag.getId(), tag);
                    else if (ArrayUtils.contains(techs, "android.nfc.tech.IsoDep"))
                        return DesfireCard.dumpTag(tag.getId(), tag);
                    else
                        throw new UnsupportedTagException(techs, Utils.getHexString(tag.getId()));
                } catch (Exception ex) {
                    mException = ex;
                    return null;
                }
            }

            @Override
            protected void onPostExecute(MifareCard card) {
                if (mException != null) {
                    if (mException instanceof UnsupportedTagException) {
                        UnsupportedTagException ex = (UnsupportedTagException) mException;
                        new AlertDialog.Builder(ReadingTagActivity.this).setTitle("Unsupported Tag")
                                .setMessage(ex.getMessage()).setCancelable(false)
                                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface arg0, int arg1) {
                                        finish();
                                    }
                                }).show();
                    } else {
                        Utils.showErrorAndFinish(ReadingTagActivity.this, mException);
                    }
                    return;
                }

                try {
                    String cardXml = Utils.xmlNodeToString(card.toXML().getOwnerDocument());

                    ContentValues values = new ContentValues();
                    values.put(CardsTableColumns.TYPE, card.getCardType().toInteger());
                    values.put(CardsTableColumns.TAG_SERIAL, Utils.getHexString(card.getTagId()));
                    values.put(CardsTableColumns.DATA, cardXml);
                    values.put(CardsTableColumns.SCANNED_AT, card.getScannedAt().getTime());

                    Uri uri = getContentResolver().insert(CardProvider.CONTENT_URI_CARD, values);
                    startActivity(new Intent(Intent.ACTION_VIEW, uri));
                    finish();
                } catch (Exception ex) {
                    Utils.showErrorAndFinish(ReadingTagActivity.this, ex);
                }
            }

            @Override
            protected void onProgressUpdate(String... values) {
                textView.setText(values[0]);
            }

        }.execute();

    } catch (Exception ex) {
        Utils.showErrorAndFinish(this, ex);
    }
}

From source file:org.deviceconnect.android.uiapp.fragment.profile.DeviceOrientationProfileFragment.java

/**
 * ?./* w  ww. java  2 s .  co  m*/
 */
private void registerEvent() {
    (new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        public DConnectMessage doInBackground(final Void... args) {
            final TextView tv = (TextView) getView().findViewById(R.id.fragment_orientation_event);
            try {
                URIBuilder builder = new URIBuilder();
                if (isSSL()) {
                    builder.setScheme("https");
                } else {
                    builder.setScheme("http");
                }
                builder.setHost(getHost());
                builder.setPort(getPort());
                builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME);
                builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION);
                builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId());
                builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());
                builder.addParameter(DConnectMessage.EXTRA_SESSION_KEY, getClientId());
                HttpResponse response = HttpEventManager.INSTANCE.registerEvent(builder, new EventHandler() {
                    @Override
                    public void onEvent(final JSONObject event) {
                        if (event != null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.setText(event.toString());
                                }
                            });
                        }
                    }
                });
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(final DConnectMessage result) {

            if (getActivity().isFinishing()) {
                return;
            }

            if (result != null) {
                TextView tv = (TextView) getView().findViewById(R.id.fragment_orientation_result);
                tv.setText(result.toString());
            }
        }
    }).execute();
}

From source file:org.deviceconnect.android.uiapp.fragment.profile.ProximityProfileFragment.java

/**
 * ?.//from   ww  w.j a v  a2  s  .  c o  m
 */
private void registerEvent() {
    (new AsyncTask<Void, Void, DConnectMessage>() {
        @Override
        public DConnectMessage doInBackground(final Void... args) {
            final TextView tv = (TextView) getView().findViewById(R.id.fragment_proximity_response);
            try {
                URIBuilder builder = new URIBuilder();
                if (isSSL()) {
                    builder.setScheme("https");
                } else {
                    builder.setScheme("http");
                }
                builder.setHost(getHost());
                builder.setPort(getPort());
                builder.setProfile(ProximityProfileConstants.PROFILE_NAME);
                builder.setAttribute(ProximityProfileConstants.ATTRIBUTE_ON_DEVICE_PROXIMITY);
                builder.addParameter(DConnectMessage.EXTRA_DEVICE_ID, getSmartDevice().getId());
                builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());
                builder.addParameter(DConnectMessage.EXTRA_SESSION_KEY, getClientId());
                HttpResponse response = HttpEventManager.INSTANCE.registerEvent(builder, new EventHandler() {
                    @Override
                    public void onEvent(final JSONObject event) {
                        if (event != null) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.setText(event.toString());
                                }
                            });
                        }
                    }
                });
                return (new HttpMessageFactory()).newDConnectMessage(response);
            } catch (IOException e) {
                Log.e("ABC", "ABC", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(final DConnectMessage result) {
            if (getActivity().isFinishing()) {
                return;
            }

            if (result != null) {
                TextView tv = (TextView) getView().findViewById(R.id.fragment_proximity_event);
                tv.setText(result.toString());
            }
        }
    }).execute();
}

From source file:weavebytes.com.futureerp.activities.DashBoardActivity.java

public void JsonParsing() {
    new AsyncTask<Void, Void, String>() {
        @Override//from  w  w  w  . j  a  va2  s .  co m
        protected void onPreExecute() {
            super.onPreExecute();
            progress.setMessage("Please Wait..");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setCancelable(true);
            progress.show();
        }

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

            if (isOnline()) {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(Config.URL + Config.U_ID);
                HttpResponse response = null;
                try {
                    response = httpClient.execute(httpget);
                    //Converting Response To JsonString
                    return ConvertResponse_TO_JSON.entityToString(response.getEntity());
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "Bad Network";
            } else {
                return "Check Your Connection";
            }
        }

        @Override
        protected void onPostExecute(String JasonString) {
            try {
                progress.dismiss();

                try {
                    JSONArray JArray;
                    JArray = new JSONArray(JasonString);
                    for (int i = 0; i < JArray.length(); i++) {

                        JSONObject obj = JArray.optJSONObject(i);
                        String name = obj.optString("name").toString();
                        arrayList.add(name);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                MyAdapter myAdapter = new MyAdapter(DashBoardActivity.this, arrayList, Config.IMG_ID);
                list = (ListView) (findViewById(R.id.list));
                list.setAdapter(myAdapter);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.execute();
}