Example usage for android.os AsyncTask execute

List of usage examples for android.os AsyncTask execute

Introduction

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

Prototype

@MainThread
public static void execute(Runnable runnable) 

Source Link

Document

Convenience version of #execute(Object) for use with a simple Runnable object.

Usage

From source file:com.almarsoft.GroundhogReader.MessageListActivity.java

private void catchupGroup() {
    AsyncTask<String, Void, Void> catchupTask = new AsyncTask<String, Void, Void>() {

        @Override//from  ww  w .  j  a va 2  s.c o  m
        protected Void doInBackground(String... groupArr) {

            try {
                mServerManager.catchupGroup(mGroup);
            } catch (IOException e) {
                Log.w("Groundhog", "Problem catching up with the server");
                e.printStackTrace();
            } catch (ServerAuthException e) {
                Log.w("Groundhog", "Problem catching up with the server");
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(Void arg0) {
            Toast.makeText(MessageListActivity.this, R.string.catchup_done, Toast.LENGTH_SHORT);
            dismissDialog(ID_DIALOG_CATCHUP);
        }
    };

    showDialog(ID_DIALOG_CATCHUP);
    catchupTask.execute(mGroup);
}

From source file:com.deployd.DeploydObject.java

public void saveInBackground(final ObjectCreateEventHandler onCreated) {
    AsyncTask<JSONObject, JSONObject, JSONObject> save = new AsyncTask<JSONObject, JSONObject, JSONObject>() {

        @Override/*from ww w  .  j  av  a  2s. c  o  m*/
        protected JSONObject doInBackground(JSONObject... params) {
            // TODO Auto-generated method stub
            try {
                JSONObject result = null;
                if (DeploydObject.this.has("id")) {
                    result = Deployd.put(params[0], "/" + resource + "/" + DeploydObject.this.getString("id"));

                    // TODO: add code for handling junctions

                } else {
                    result = Deployd.post(params[0], "/" + resource);
                }
                return result;
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            // TODO Auto-generated method stub
            if (result != null) {
                if (onCreated != null) {
                    try {
                        DeploydObject.this.put("id", result.getString("id"));

                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    onCreated.objectCreated(DeploydObject.this);
                }
            }
            super.onPostExecute(result);
        }
    };
    save.execute(this);
}

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/* w w  w  .  j  av a2  s.co m*/
        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.example.carrie.carrie_test1.druginfo.java

private void load_data_from_server_notsearch(int id) {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override/*from w ww . ja va  2s.  c o  m*/
        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_list1.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.owncloud.android.ui.fragment.contactsbackup.ContactsBackupFragment.java

private void refreshBackupFolder(final String backupFolderPath,
        final ContactsPreferenceActivity contactsPreferenceActivity) {
    AsyncTask<String, Integer, Boolean> task = new AsyncTask<String, Integer, Boolean>() {
        @Override//from   w  w  w.j ava2s. c o m
        protected Boolean doInBackground(String... path) {
            FileDataStorageManager storageManager = new FileDataStorageManager(account,
                    getActivity().getContentResolver());

            OCFile folder = storageManager.getFileByPath(path[0]);

            if (folder != null) {
                RefreshFolderOperation operation = new RefreshFolderOperation(folder,
                        System.currentTimeMillis(), false, false, false, storageManager, account, getContext());

                RemoteOperationResult result = operation.execute(account, getContext());
                return result.isSuccess();
            } else {
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                OCFile backupFolder = contactsPreferenceActivity.getStorageManager()
                        .getFileByPath(backupFolderPath);

                Vector<OCFile> backupFiles = contactsPreferenceActivity.getStorageManager()
                        .getFolderContent(backupFolder, false);

                if (backupFiles == null || backupFiles.size() == 0) {
                    contactsDatePickerBtn.setVisibility(View.GONE);
                } else {
                    contactsDatePickerBtn.setVisibility(View.VISIBLE);
                }
            }
        }
    };

    task.execute(backupFolderPath);
}

From source file:jp.mixi.android.sdk.MixiContainerImpl.java

@Override
public void send(final String endpointPath, final String contentType, final InputStream stream,
        final long length, final CallbackListener listener) {

    AsyncTask<Void, Void, Void> tasc = new AsyncTask<Void, Void, Void>() {
        private Exception e;

        @Override//  w  ww.j  a v a2 s.  co m
        protected Void doInBackground(Void... params) {
            try {
                refreshToken();
            } catch (RemoteException e) {
                this.e = e;
            } catch (ApiException e) {
                this.e = e;
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void res) {
            if (e == null) {
                send(endpointPath, contentType, HttpMethod.POST, stream, length, listener);
            } else {
                Log.v(TAG, "refresh token error");
                listener.onFatal(new ErrorInfo(e));
            }
        }
    };
    tasc.execute(null);
}

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

private void load_data_from_server_search(final String search) {
    AsyncTask<Integer, Void, Void> task = new AsyncTask<Integer, Void, Void>() {
        @Override//  ww  w  .  java 2  s. c  o m
        protected Void doInBackground(Integer... integers) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("http://54.65.194.253/Drug/search.php?search=" + search)
                    .build();
            Log.d("searchtest", "4");
            try {
                Response response = client.newCall(request).execute();

                JSONArray array = new JSONArray(response.body().string());
                Log.d("searchtest", array.toString());
                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_list2.add(mydata);
                }
                Log.d("searchtest", "5");

            } 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(1);
}

From source file:com.twitterdev.rdio.app.RdioApp.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();/*from w  ww  . j  ava  2  s . c om*/
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            final String trackName = track.artistName;
            final String artist = track.trackName;
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
                new getSearch().execute(track.trackName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView a = (TextView) findViewById(R.id.artist);
                        //a.setText(artist);
                        TextView t = (TextView) findViewById(R.id.track);
                        //t.setText(trackName);
                    }
                });

            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                int imageWidth = artwork.getWidth();
                int imageHeight = artwork.getHeight();
                DisplayMetrics dimension = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dimension);
                int newWidth = dimension.widthPixels;

                float scaleFactor = (float) newWidth / (float) imageWidth;
                int newHeight = (int) (imageHeight * scaleFactor);

                artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true);
                //albumArt.setImageBitmap(bitmap);

                albumArt.setAdjustViewBounds(true);
                albumArt.setImageBitmap(artwork);

            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    //Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

From source file:apps.junkuvo.alertapptowalksafely.MainActivity.java

private void tweet(String tweetString) {
    AsyncTask<String, Void, Boolean> task = new AsyncTask<String, Void, Boolean>() {
        @Override/*  www .j  a  v a2s . co  m*/
        protected Boolean doInBackground(String... params) {
            try {
                mTwitter.updateStatus(params[0]);
                return true;
            } catch (TwitterException e) {
                e.printStackTrace();
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                FlurryAgent.logEvent(getApplicationContext().getString(R.string.twitter_tweet_succeed));
                Toast.makeText(getApplicationContext(),
                        getApplicationContext().getString(R.string.twitter_tweet_succeed), Toast.LENGTH_LONG)
                        .show();
            } else {
                Toast.makeText(getApplicationContext(),
                        getApplicationContext().getString(R.string.twitter_tweet_fail), Toast.LENGTH_LONG)
                        .show();
            }
        }
    };
    task.execute(tweetString);
}

From source file:com.artur.softwareproject.Main.java

private void stopRecording() {
    final Context context = this;

    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
        @Override//from  ww w  . j a  v  a2 s  .  c o m
        protected void onPreExecute() {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing...");
            pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pd.setMessage("Please wait.");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            modelConstructed = rService.create3dModel();

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            if (pd != null) {
                pd.dismiss();
            }

            if (rBound) {
                unbindService(mConnection);
                rBound = false;
            }

            MenuItem item = mainMenu.findItem(R.id.record_data);

            item.setIcon(R.drawable.ic_action_save);

            Animation a = AnimationUtils.loadAnimation(context, R.anim.textupslide);
            TextView tv = (TextView) findViewById(R.id.recordClock);
            tv.startAnimation(a);

            recordClock.setVisibility(View.GONE);

            recording = false;

            if (modelConstructed) {
                Toast.makeText(getApplicationContext(), "Recording stopped.\n3D model created.",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), "Recording stopped.\n3D model creation failed.",
                        Toast.LENGTH_LONG).show();
            }
        }
    };

    task.execute((Void[]) null);

}