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.nononsenseapps.filepicker.sample.ftp.FtpPickerFragment.java

/**
 * Name is validated to be non-null, non-empty and not containing any
 * slashes.//from   w w  w  . j  av a2  s .  c  o  m
 *
 * @param name The name of the folder the user wishes to create.
 */
@Override
public void onNewFolder(@NonNull String name) {
    AsyncTask<String, Void, FtpFile> task = new AsyncTask<String, Void, FtpFile>() {

        @Override
        protected FtpFile doInBackground(String... names) {
            FtpFile result = null;
            if (names.length > 0) {
                result = onNewFolderAsync(names[0]);
            }
            return result;
        }

        @Override
        protected void onPostExecute(FtpFile folder) {
            if (folder != null) {
                refresh(folder);
            } else {
                Toast.makeText(getContext(), R.string.nnf_create_folder_error, Toast.LENGTH_SHORT).show();
            }
        }
    };
    task.execute(name);
}

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

private void load_data_from_server(int id) {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override/*from   w w w.  j a 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);

                    MyData mydata = new MyData(object.getInt("id"), object.getString("chineseName"),
                            object.getString("image"), object.getString("indication"),
                            object.getString("englishName"), object.getString("licenseNumber"),
                            object.getString("category"), object.getString("component"),
                            object.getString("maker_Country"), object.getString("applicant"),
                            object.getString("maker_Name"), object.getString("QRCode"));

                    data_list.add(mydata);
                }

            } 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.dealsmessanger.android.DemoActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>// w  ww . j a va 2 s .  c om
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
                }
                regid = gcm.register(SENDER_ID);
                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) {
            //etRegId.setText(msg + "\n");
            DeviceIdentifier deviceIdenifier = (DeviceIdentifier) getApplicationContext();
            deviceIdenifier.setGcmRegId(msg);
        }
    }.execute(null, null, null);
}

From source file:com.tesobe.hello_obp.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    privateAccountsJsonView = (TextView) findViewById(R.id.private_accounts_json);

    // Request the banks available from the API
    new AsyncTask<Void, Void, String>() {

        @Override//from   w w w .j  av a  2 s  .c  o m
        /**
         * @return A String containing the json representing the available banks, or an error message
         */
        protected String doInBackground(Void... params) {
            try {
                JSONObject banksJson = OBPRestClient.getBanksJson();
                return banksJson.toString();
            } catch (ExpiredAccessTokenException e) {
                // login again / re-authenticate
                redoOAuth();
                return "";
            } catch (ObpApiCallFailedException e) {
                return "Sorry, there was an error!";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            privateAccountsJsonView.setText(result);
        }
    }.execute();
}

From source file:com.clover.android.sdk.examples.InventoryTestActivity.java

private void fetchItemsFromService() {
    if (serviceIsBound && inventoryService != null) {
        new AsyncTask<Void, Void, Item>() {
            @Override
            protected Item doInBackground(Void... params) {
                Item item = null;/*from   w  w  w .java 2 s  .  c  o  m*/
                try {
                    ResultStatus getItemsStatus = new ResultStatus();
                    List<Item> items = inventoryService.getItems(getItemsStatus);
                    Log.i(TAG, "Received result from getItems(): " + getItemsStatus);
                    if (getItemsStatus.isSuccess()) {
                        for (Item i : items) {
                            Log.i(TAG, "item = " + dumpItem(i));
                        }
                    }
                    if (items != null && items.size() > 0) {
                        String itemId = items.get(0).getId();
                        ResultStatus getItemStatus = new ResultStatus();
                        item = inventoryService.getItem(itemId, getItemStatus);
                        Log.i(TAG, "Received result from getItem(): " + getItemStatus);
                    }

                    ResultStatus resultStatus = new ResultStatus();
                    List<Category> categories = inventoryService.getCategories(resultStatus);
                    if (resultStatus.isSuccess()) {
                        for (Category category : categories) {
                            Log.i(TAG, "category = " + dumpCategory(category));
                        }
                    } else {
                        Log.i(TAG, "Couldn't retrieve categories: " + resultStatus);
                    }
                    List<TaxRate> taxRates = inventoryService.getTaxRates(resultStatus);
                    if (resultStatus.isSuccess()) {
                        for (TaxRate taxRate : taxRates) {
                            Log.i(TAG, "tax rate = " + dumpTaxRate(taxRate));
                        }
                    } else {
                        Log.i(TAG, "Couldn't retrieve tax rates: " + resultStatus);
                    }
                } catch (RemoteException e) {
                    Log.e(TAG, "Error calling inventory service", e);
                }
                return item;
            }

            @Override
            protected void onPostExecute(Item result) {
                displayItem(result);
            }
        }.execute();
    }
}

From source file:ca.ualberta.cmput301.t03.MainActivity.java

/**
 * Load the first fragment and load the username and email fields of the nav bar header.
 *//*from   w w w. ja  v  a2 s . co m*/
public void finishOnCreate() {
    addInitialFragment();
    AsyncTask task = new AsyncTask() {
        private String email = "";
        private String username = "";

        @Override
        protected Object doInBackground(Object[] params) {
            username = PrimaryUser.getInstance().getUsername();
            String emailTemp = "";
            try {
                emailTemp = PrimaryUser.getInstance().getProfile().getEmail();
            } catch (IOException e) {
                emailTemp = "";
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("App is offline.", e);
            }

            email = emailTemp;

            try {
                PrimaryUser.getInstance().getProfile().addObserver(MainActivity.this);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("App is offline.", e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            sidebarUsernameTextView.setText(username);
            sidebarEmailTextView.setText(email);
        }
    };

    task.execute();

}

From source file:com.nokia.example.pepperfarm.iap.Payment.java

/**
 * Check the products that we have already purchased
 *//*  www . j a v a 2  s . c om*/
public void getPurchases(boolean ignoreLifeCycleCheck) {

    if (!isBillingAvailable())
        return;

    if (ignoreLifeCycleCheck == false) {
        if (purchases_asked) {
            Log.i("getPurchases", "Restorables already asked.");
            return;
        }
    }

    MainScreenPepperListFragment.getpeppers.setVisibility(View.INVISIBLE);
    MainScreenPepperListFragment.fetch_peppers_progressbar.setVisibility(View.VISIBLE);
    MainScreenPepperListFragment.fetching_peppers.setVisibility(View.VISIBLE);

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

        @Override
        protected Void doInBackground(Void... params) {
            ArrayList<String> productIdArray = new ArrayList<String>(Content.ITEM_MAP.keySet());
            Bundle productBundle = new Bundle();
            productBundle.putStringArrayList("ITEM_ID_LIST", productIdArray);

            try {
                Bundle purchases = npay.getPurchases(API_VERSION, activity.getPackageName(), ITEM_TYPE_INAPP,
                        productBundle, null);
                Log.i("getPurchases",
                        "GET PURCHASES RESPONSE CODE: " + purchases.getInt("RESPONSE_CODE", RESULT_ERR));

                if (purchases.getInt("RESPONSE_CODE", RESULT_ERR) == RESULT_OK) {

                    ArrayList<String> purchaseDataList = purchases
                            .getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                    for (String purchaseData : purchaseDataList) {
                        parsePurchaseData(purchaseData);
                    }
                    purchases_asked = true;
                } else {
                    Log.e("getPurchases", "GET PURCHASES - response was not ok: Result was: "
                            + purchases.getInt("RESPONSE_CODE", RESULT_ERR));
                }

            } catch (JSONException e) {
                Log.e("getPurchases", "PURCHASE DATA PARSING EXCEPTION: " + e.getMessage(), e);
            } catch (RemoteException e) {
                Log.e("getPurchases", "EXCEPTION: " + e.getMessage(), e);
            }
            return null;
        }

        private void parsePurchaseData(String purchaseData) throws JSONException {

            Purchase purchase = new Purchase(purchaseData);

            Product p = Content.ITEM_MAP.get(purchase.getProductId());

            if (p != null) {
                p.setPurchased(purchase);
                Log.i("getPurchases", "Restoring product " + purchase.getProductId() + " Purchase token: "
                        + purchase.getToken());
            } else {
                Log.i("getPurchases",
                        "Unable to restore product " + purchase.getProductId() + ". Product not found.");
            }

        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            MainScreenPepperListFragment.getpeppers.setVisibility(View.VISIBLE);
            MainScreenPepperListFragment.fetch_peppers_progressbar.setVisibility(View.GONE);
            MainScreenPepperListFragment.fetching_peppers.setVisibility(View.GONE);

            if (ProductListFragment.purchaseListAdapter != null) {
                ProductListFragment.purchaseListAdapter.notifyDataSetChanged();
            }
            if (MainScreenPepperListFragment.reference.adapter != null) {
                MainScreenPepperListFragment.reference.adapter.notifyDataSetChanged();
            }
        }

    };
    restoreTask.execute();
}

From source file:at.jclehner.rxdroid.Backup.java

private static void encryptAll(final Context context, final String key, final Runnable callback) {
    new AsyncTask<Void, String, Exception>() {
        private ProgressDialog mDialog;
        private List<File> mFiles;

        @Override//from   www . j  av a 2  s . c  o  m
        protected void onPreExecute() {
            mFiles = Backup.getBackupFiles(context);

            mDialog = new ProgressDialog(context);
            mDialog.setTitle(R.string._msg_encrypting);
            mDialog.setCancelable(false);
            mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mDialog.setIndeterminate(false);
            mDialog.setMax(mFiles.size());
            mDialog.setProgress(0);
            mDialog.show();
        }

        @Override
        protected Exception doInBackground(Void... params) {
            int progress = 0;

            for (File file : mFiles) {
                try {
                    Backup.encrypt(context, file, key);
                } catch (IOException | ZipException e) {
                    Log.w(TAG, e);
                    return e;
                }

                mDialog.setProgress(progress++);
            }

            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPostExecute(Exception e) {
            if (mDialog != null) {
                mDialog.dismiss();
                mDialog = null;
            }

            if (e != null)
                Util.showExceptionDialog(mDialog.getContext(), e);
            else if (callback != null)
                callback.run();

        }
    }.execute();
}

From source file:org.droid2droid.internal.AbstractRemoteAndroidImpl.java

@Override
public boolean bindService(final Intent service, final ServiceConnection conn, final int flags) {

    new AsyncTask<Void, Void, Void>() {
        @Override// www . j a  v  a  2s .com
        protected Void doInBackground(Void... v) {
            try {
                ComponentName[] name = new ComponentName[1];
                int oid = bindOID(getConnectionId(), System.identityHashCode(conn), service, flags, name,
                        mExecuteTimeout);
                if (oid == -1)
                    PostTools.postServiceDisconnected(conn, name[0]);
                else {
                    RemoteBinderProxy proxy = new RemoteBinderProxy(AbstractRemoteAndroidImpl.this, oid);
                    Binded disconnect = new Binded();
                    disconnect.name = name[0];
                    disconnect.conn = conn;
                    disconnect.proxy = proxy;
                    synchronized (mBinders) {
                        mBinders.put(conn, disconnect);
                    }
                    PostTools.postServiceConnected(conn, name[0], proxy);
                }
            } catch (SecurityException e) {
                if (E)
                    Log.e(TAG_SECURITY, PREFIX_LOG + "Refuse connexion", e);
                close();
            } catch (RemoteException e) {
                PostTools.postServiceDisconnected(conn, null); // FIXME: null en ComponentName ?
            }
            return null;
        }
    }.execute();
    return true;
}

From source file:com.odoo.addons.crm.models.CRMLead.java

public void convertToOpportunity(final ODataRow lead, final List<Integer> other_lead_ids,
        final OnOperationSuccessListener listener) {
    new AsyncTask<Void, Void, Void>() {
        private ProgressDialog dialog;

        @Override/*from w ww. j av  a  2 s  . c  om*/
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(mContext);
            dialog.setTitle(R.string.title_please_wait);
            dialog.setMessage(OResource.string(mContext, R.string.title_working));
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                odoo.Odoo odoo = getServerDataHelper().getOdoo();
                // Creating wizard record
                JSONObject values = new JSONObject();
                values.put("name", (other_lead_ids.size() > 0) ? "merge" : "convert");
                Object partner_id = false;
                ODataRow partner = null;
                if (!lead.getString("partner_id").equals("false")) {
                    ResPartner resPartner = new ResPartner(mContext, getUser());
                    partner = resPartner.browse(lead.getInt("partner_id"));
                    partner_id = partner.getInt("id");
                }
                values.put("action", (partner == null) ? "create" : "exist");
                values.put("partner_id", partner_id);

                JSONObject context = new JSONObject();
                context.put("stage_type", "lead");
                context.put("active_id", lead.getInt("id"));
                other_lead_ids.add(lead.getInt("id"));
                context.put("active_ids", JSONUtils.<Integer>toArray(other_lead_ids));
                context.put("active_model", "crm.lead");
                odoo.updateContext(context);
                JSONObject result = odoo.createNew("crm.lead2opportunity.partner", values);
                int lead_to_opp_partner_id = result.getInt("result");

                // Converting lead to opportunity
                OArguments arg = new OArguments();
                arg.add(lead_to_opp_partner_id);
                arg.add(context);
                odoo.call_kw("crm.lead2opportunity.partner", "action_apply", arg.get());
                OValues val = new OValues();
                val.put("type", "opportunity");
                for (int id : other_lead_ids) {
                    update(selectRowId(id), val);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            dialog.dismiss();
            if (listener != null) {
                listener.OnSuccess();
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
            if (listener != null) {
                listener.OnCancelled();
            }
        }
    }.execute();
}