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:ch.gianulli.flashcards.ListsFragment.java

@Override
public void onRefresh() {
    if (mListLoader != null) {
        mListLoader.cancel(true);/*from   w ww .  ja va 2  s.c o m*/
        mListLoader = null;
    }

    mListLoader = new AsyncTask<Void, Void, ArrayList<TrelloList>>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mAdapter.isEmpty()) {
                setActivePage(Page.PROGRESS);
                mRefreshLayout.setRefreshing(false);
            } else {
                setActivePage(Page.LIST_LIST);
                mRefreshLayout.setRefreshing(true);
            }
        }

        @Override
        protected ArrayList<TrelloList> doInBackground(Void... params) {
            try {
                return mBoard.getAllLists(mTrelloApi);
            } catch (TrelloNotAuthorizedException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTrelloApi.requestAuthorization(getActivity().getSupportFragmentManager());
                    }
                });
            } catch (TrelloNotAccessibleException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setActivePage(Page.NO_CONNECTION);
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<TrelloList> lists) {
            mRefreshLayout.setRefreshing(false);

            mAdapter.setLists(lists);
            if (lists != null) {
                if (mAdapter.isEmpty()) {
                    setActivePage(Page.NO_BOARDS);
                } else {
                    setActivePage(Page.LIST_LIST);
                }
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:ch.gianulli.flashcards.SessionFragment.java

private void fetchCards() {
    if (mCardsLoader != null) {
        mCardsLoader.cancel(true);//w  w  w .j  a va2s. co  m
        mCardsLoader = null;
    }

    mCardsLoader = new AsyncTask<Void, Void, Boolean>() {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            setActivePage(Page.PROGRESS);
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            try {
                mList = TrelloList.getList(mTrelloApi, null, mListId);

                if (mList != null) {

                    // Select cards
                    mCards = mList.getCards();

                    int mode = getArguments().getInt(KEY_MODE);
                    int n = getArguments().getInt(KEY_NBR_OF_CARDS);
                    if (mode == SessionActivity.MODE_AT_RANDOM) {
                        mCards = new ArrayList<>(mCards); // cards in list stay untouched
                        Collections.shuffle(mCards);
                        mCards = new ArrayList<>(mCards.subList(0, Math.min(n, mCards.size())));
                    } else if (mode == SessionActivity.MODE_FROM_TOP) {
                        mCards = new ArrayList<>(mCards.subList(0, Math.min(n, mCards.size())));
                    } else if (mode == SessionActivity.MODE_FROM_BOTTOM) {
                        mCards = new ArrayList<>(mCards.subList(Math.max(0, mCards.size() - n), mCards.size()));
                        Collections.reverse(mCards);
                    }

                    return true;
                } else {
                    throw new TrelloNotAccessibleException("Result was null.");
                }
            } catch (TrelloNotAuthorizedException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTrelloApi.requestAuthorization(getActivity().getSupportFragmentManager());
                    }
                });
            } catch (TrelloNotAccessibleException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setActivePage(Page.NO_CONNECTION);
                    }
                });
                Log.d("test", "Trello not accessible: " + e.getMessage());
            }

            return false;
        }

        @Override
        protected void onPostExecute(Boolean success) {
            if (success) {
                mAdapter.setCards(mCards);
                setActivePage(Page.SESSION_VIEW);

                mViewPager.setCurrentItem(0);

                // Update page indicator
                mPageIndicator.setText(getResources().getString(R.string.page_indicator_text,
                        mViewPager.getCurrentItem() + 1, mAdapter.getCount()));
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.parse.f8.model.Favorites.java

/**
 * Loads the set of favorites from the SharedPreferences file, calling the
 * listeners for all the favorites that get added.
 *//*from w  w  w  .  j ava2 s .  c  o  m*/
public void findLocally(final Context context) {
    new AsyncTask<Void, Void, JSONObject>() {
        @Override
        protected JSONObject doInBackground(Void... unused) {
            SharedPreferences prefs = context.getSharedPreferences("favorites.json", Context.MODE_PRIVATE);
            String jsonString = prefs.getString("json", "{}");
            try {
                return new JSONObject(jsonString);
            } catch (JSONException json) {
                // Just ignore malformed json.
                return null;
            }
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            if (json != null) {
                setJSON(json);
            }
        }
    }.execute();
}

From source file:com.piusvelte.sonet.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();//from w  w  w.j a v a  2  s . c o  m
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = sonetCrypto.Decrypt(account.getString(0));
                mSecret = sonetCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute(mAccountId);
}

From source file:com.google.android.gcm.demo.logic.DeviceGroupsHelper.java

/**
 * Execute in background the HTTP calls to add and remove members.
 *//*from   w w w.  j  a  v a 2s . co  m*/
public void asyncUpdateGroup(final String senderId, final String apiKey, final String groupName,
        final String groupKey, Bundle newMembers, Bundle removedMembers) {
    final Bundle members2Add = new Bundle(newMembers);
    final Bundle members2Remove = new Bundle(removedMembers);
    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... voids) {
            if (members2Add.size() > 0) {
                addMembers(senderId, apiKey, groupName, groupKey, members2Add);
            }
            if (members2Remove.size() > 0) {
                removeMembers(senderId, apiKey, groupName, groupKey, members2Remove);
            }
            return null;
        }
    }.execute();
}

From source file:android.support.v17.leanback.supportleanbackshowcase.app.grid.VideoGridExampleFragment.java

/**
 * Fetches videos metadata from urlString on a background thread. Callback methods are invoked
 * upon success or failure of this fetching.
 * @param urlString The json file url to fetch from
 *//*from  w  w  w .ja v  a 2  s  . co m*/
private void fetchVideosInfo(final String urlString) {

    new AsyncTask<Void, Void, FetchResult>() {
        @Override
        protected void onPostExecute(FetchResult fetchResult) {
            if (fetchResult.isSuccess) {
                onFetchVideosInfoSuccess(fetchResult.jsonObj);
            } else {
                onFetchVideosInfoError(fetchResult.exception);
            }
        }

        @Override
        protected FetchResult doInBackground(Void... params) {
            BufferedReader reader = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(urlString);
                urlConnection = (HttpURLConnection) url.openConnection();
                reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "utf-8"));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                return new FetchResult(new JSONObject(sb.toString()));
            } catch (JSONException ex) {
                Log.e(TAG, "A JSON error occurred while fetching videos: " + ex.toString());
                return new FetchResult(ex);
            } catch (IOException ex) {
                Log.e(TAG, "An I/O error occurred while fetching videos: " + ex.toString());
                return new FetchResult(ex);
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ex) {
                        Log.e(TAG, "JSON reader could not be closed! " + ex);
                    }
                }
            }
        }
    }.execute();
}

From source file:com.kabootar.GlassMemeGenerator.ImageOverlay.java

public static boolean saveToSD(final Bitmap overlaid, final String sdPath, final String fileName) {
    boolean isItSaved = false;
    new AsyncTask<Void, Void, Void>() {

        @Override/*  w ww  .j  ava 2 s  . c  o m*/
        protected Void doInBackground(Void... arg0) {

            File image = new File(sdPath, fileName);

            FileOutputStream outStream;
            try {

                outStream = new FileOutputStream(image);
                //resize image
                Bitmap newoverlaid = getResizedBitmap(overlaid, 1000, 1362);
                newoverlaid.compress(Bitmap.CompressFormat.PNG, 100, outStream);

                outStream.flush();
                outStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
            int width = bm.getWidth();
            int height = bm.getHeight();
            float scaleWidth = ((float) newWidth) / width;
            float scaleHeight = ((float) newHeight) / height;
            // CREATE A MATRIX FOR THE MANIPULATION
            Matrix matrix = new Matrix();
            // RESIZE THE BIT MAP
            matrix.postScale(scaleWidth, scaleHeight);

            // "RECREATE" THE NEW BITMAP
            Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
            return resizedBitmap;
        }

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

    return isItSaved;
}

From source file:net.stefanopallicca.android.awsmonitor.MainActivity.java

/**
 * Registers the application with GCM servers asynchronously.
 * <p>//from www. j  ava  2  s  .  co m
 * Stores the registration ID and the app versionCode in the application's
 * shared preferences.
 * @return 
 */
private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {

        ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("Processing...");
            pd.setMessage("Please wait.");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        }

        @Override
        protected String doInBackground(Void... params) {
            String msg = "";
            try {
                if (gcm == null) {
                    gcm = GoogleCloudMessaging.getInstance(context);
                }
                regid = gcm.register(SENDER_ID);
                //msg = "Device registered, registration ID=" + regid;

                // Persist the regID - no need to register again.

                storeRegistrationId(context, regid);
                /**
                 * Send regid to GSN server
                 */
                try {
                    if (server.sendRegistrationIdToBackend(regid))
                        msg = "ok";
                    else
                        msg = "ko";
                } catch (HttpException e) {
                    msg = "ko";
                }
            } catch (IOException ex) {
                msg = "ko";
            }
            return msg;
        }

        @Override
        protected void onPostExecute(String msg) {
            //mDisplay.append(msg + "\n");
            if (msg == "ok") {
                Context context = getApplicationContext();
                CharSequence text = getString(R.string.device_registered) + " "
                        + MainActivity.this._sharedPref.getString("pref_server_url", "") + ":"
                        + MainActivity.this._sharedPref.getString("pref_server_port", "");
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            } else {
                Context context = getApplicationContext();
                CharSequence text = getString(R.string.error_connecting) + " "
                        + MainActivity.this._sharedPref.getString("pref_server_url", "") + ":"
                        + MainActivity.this._sharedPref.getString("pref_server_port", "");
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
            pd.cancel();
            launchMainApp();
        }
    }.execute(null, null, null);
}

From source file:info.xuluan.podcast.SearchActivity.java

private void start_search(String search_url) {
    SearchActivity.this.progress = ProgressDialog.show(SearchActivity.this,
            getResources().getText(R.string.dialog_title_loading),
            getResources().getText(R.string.dialog_message_loading), true);
    AsyncTask<String, ProgressDialog, String> asyncTask = new AsyncTask<String, ProgressDialog, String>() {
        String url;//  w w  w.  j  a v  a2  s  .c  o  m

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

            url = params[0];
            // log.debug("doInBackground URL ="+url);
            return fetchChannelInfo(url);

        }

        @Override
        protected void onPostExecute(String result) {

            if (SearchActivity.this.progress != null) {
                SearchActivity.this.progress.dismiss();
                SearchActivity.this.progress = null;
            }

            if (result == null) {
                Toast.makeText(SearchActivity.this, getResources().getString(R.string.network_fail),
                        Toast.LENGTH_SHORT).show();
            } else {
                List<SearchItem> items = parseResult(result);
                if (items.size() == 0) {
                    Toast.makeText(SearchActivity.this, getResources().getString(R.string.no_data_found),
                            Toast.LENGTH_SHORT).show();
                } else {
                    mStart += items.size();
                    for (int i = 0; i < items.size(); i++) {
                        mItems.add(items.get(i));
                        mAdapter.add(items.get(i).title);

                    }
                }
            }

            updateBtn();
        }
    };
    asyncTask.execute(search_url);
}

From source file:app.screen.ServiceControlFragment.java

/** wire the button to the db */
private void _wireDbButton() {
    // onClick behavior for button
    myViews.btn_testdb.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            new AsyncTask<Void, Void, Void>() {
                protected Void doInBackground(Void... voids) {

                    try {
                        getAppData().dbManager.test();
                    } catch (Exception e) {
                        AndroidUtils.logErr(IconPaths.MyApp,
                                String.format("ServiceControlFragment - problem running db test, error is: %s",
                                        e.toString()));
                    }/*from  www.jav a2 s.c o m*/
                    return null;
                }

                protected void onPreExecute() {
                    myViews.btn_testdb.setEnabled(false);
                }

                protected void onPostExecute(Void aVoid) {
                    myViews.btn_testdb.setEnabled(true);
                    Toast.makeText(activity, "DB Test Completed", Toast.LENGTH_SHORT).show();
                }
            }.execute();
        }
    });
}