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:ca.ualberta.cmput301.t03.inventory.BrowseInventoryFragment.java

/**
 * Starts intent for inspecting item/*from  w ww.j av a 2s  .co  m*/
 *
 * @param item
 */
public void inspectItem(Item item) {
    AsyncTask<Item, Void, Intent> findItemOwnerAndStartInspectItemActivity = new AsyncTask<Item, Void, Intent>() {
        @Override
        protected Intent doInBackground(Item[] items) {
            Intent intent = new Intent(getContext(), InspectItemView.class);
            try {
                for (User friend : PrimaryUser.getInstance().getFriends().getFriends()) {
                    if (friend.getInventory().getItems().containsKey(items[0].getUuid())) {
                        intent.putExtra("user", friend.getUsername());
                        intent.putExtra("ITEM_UUID", items[0].getUuid().toString());
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ServiceNotAvailableException e) {
                throw new RuntimeException("App is offline.", e);
            }
            return intent;
        }

        @Override
        protected void onPostExecute(Intent i) {
            super.onPostExecute(i);
            startActivity(i);
        }
    };
    findItemOwnerAndStartInspectItemActivity.execute(item);
}

From source file:com.chao.facebookzc.widget.LoginButton.java

private void checkNuxSettings() {
    if (nuxMode == ToolTipMode.DISPLAY_ALWAYS) {
        String nuxString = getResources().getString(R.string.com_facebook_tooltip_default);
        displayNux(nuxString);//  w  w  w.  j  ava  2 s  .  c o  m
    } else {
        // kick off an async request
        final String appId = Utility.getMetadataApplicationId(getContext());
        AsyncTask<Void, Void, FetchedAppSettings> task = new AsyncTask<Void, Void, Utility.FetchedAppSettings>() {
            @Override
            protected FetchedAppSettings doInBackground(Void... params) {
                FetchedAppSettings settings = Utility.queryAppSettings(appId, false);
                return settings;
            }

            @Override
            protected void onPostExecute(FetchedAppSettings result) {
                showNuxPerSettings(result);
            }
        };
        task.execute((Void[]) null);
    }

}

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  ww  . ja va 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/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.music.mybarr.activities.ExampleActivity.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();//  ww w .j  av a2 s.  c  o m
        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];
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
            } 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) {
                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:org.linphone.ChatListFragment.java

@Override
public void onResume() {
    super.onResume();

    //Check if the is the first time we show the chat view since we use liblinphone chat storage
    useLinphoneStorage = getResources().getBoolean(R.bool.use_linphone_chat_storage);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LinphoneActivity.instance());
    boolean updateNeeded = prefs.getBoolean(getString(R.string.pref_first_time_linphone_chat_storage), true);
    updateNeeded = updateNeeded && !isVersionUsingNewChatStorage();
    if (useLinphoneStorage && updateNeeded) {
        AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
            private ProgressDialog pd;

            @Override/*from  www .ja va2s  . c  o m*/
            protected void onPreExecute() {
                pd = new ProgressDialog(LinphoneActivity.instance());
                pd.setTitle(getString(R.string.wait));
                pd.setMessage(getString(R.string.importing_messages));
                pd.setCancelable(false);
                pd.setIndeterminate(true);
                pd.show();
            }

            @Override
            protected Void doInBackground(Void... arg0) {
                try {
                    if (importAndroidStoredMessagedIntoLibLinphoneStorage()) {
                        prefs.edit()
                                .putBoolean(getString(R.string.pref_first_time_linphone_chat_storage), false)
                                .commit();
                        LinphoneActivity.instance().getChatStorage().restartChatStorage();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                pd.dismiss();
            }
        };
        task.execute((Void[]) null);
    }

    if (LinphoneActivity.isInstanciated()) {
        LinphoneActivity.instance().selectMenu(FragmentsAvailable.CHATLIST);
        LinphoneActivity.instance().updateChatListFragment(this);

        if (getResources().getBoolean(R.bool.show_statusbar_only_on_dialer)) {
            LinphoneActivity.instance().hideStatusBar();
        }
    }

    refresh();
}

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;/*from w  w w  . j  a v  a  2  s  . com*/

        @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:com.fowlcorp.homebank4android.MainActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { //called when an activity whith result ends
    if (requestCode == DROP_PATH_OK) {
        if (resultCode == Activity.RESULT_OK) { //if the filechooser end correctly
            String result = data.getStringExtra("pathResult"); //store the new path in the preferences
            sharedPreferences.edit().putString("dropPath", result).commit();
            initParserFile();//w w  w  .j  a va  2 s  .co  m
            doTEst();
            updateGUI();
        }
    } else if (requestCode == FIRST_OK) {
        sharedPreferences.edit().putBoolean("isFirstLaunch", false).commit();
        AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {

            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                drawerLayout.setVisibility(View.GONE);
                super.onPreExecute();
            }

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

                try {
                    initParserFile();
                    doTEst();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                progressBar.setVisibility(View.GONE);
                drawerLayout.setVisibility(View.VISIBLE);
                //               Log.d("Debug", "End of parsing");
                //               Log.d("Debug", String.valueOf(model.getGrandTotalBank()));
                //model.updateGrandTotal();
                try {
                    updateGUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        asyncTask.execute("");

    } else if (requestCode == SETTINGS_OK) {
        updateGUI();
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }

}

From source file:com.fowlcorp.homebank4android.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);

    super.onCreate(savedInstanceState); //restore the saved state

    setContentView(R.layout.toolbar_layout); //invoke the layout

    toolBar = (Toolbar) findViewById(R.id.toolbar);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    setSupportActionBar(toolBar);/*from  w  w w . j ava  2  s .  com*/

    //invoke the fragment
    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mNavigationDrawerFragment.setRetainInstance(true); //use for orientation change
    mTitle = getTitle(); //set the title of the fragment (name of the app by default)

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    if (sharedPreferences.getBoolean("isFirstLaunch", true)) {
        Intent intent = new Intent(getApplicationContext(), firstLaunchActivity.class);
        startActivityForResult(intent, FIRST_OK); //start an activity to select a valide file
    } else {

        AsyncTask<String, String, String> asyncTask = new AsyncTask<String, String, String>() {

            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                drawerLayout.setVisibility(View.GONE);
                super.onPreExecute();
            }

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

                try {
                    initParserFile();
                    doTEst();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                // TODO Auto-generated method stub
                super.onPostExecute(result);
                progressBar.setVisibility(View.GONE);
                drawerLayout.setVisibility(View.VISIBLE);
                //               Log.d("Debug", "End of parsing");
                //               Log.d("Debug", String.valueOf(model.getGrandTotalBank()));
                //model.updateGrandTotal();
                try {
                    updateGUI();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        asyncTask.execute("");
    }
}

From source file:com.xperia64.timidityae.Globals.java

public static boolean initialize(final Activity a) {
    if (firstRun) {
        final File rootStorage = new File(
                Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (!rootStorage.exists()) {
            rootStorage.mkdir();// w w  w .  j av a 2s .c  om
        }
        File playlistDir = new File(rootStorage.getAbsolutePath() + "/playlists/");
        if (!playlistDir.exists()) {
            playlistDir.mkdir();
        }
        File tcfgDir = new File(rootStorage.getAbsolutePath() + "/timidity/");
        if (!tcfgDir.exists()) {
            tcfgDir.mkdir();
        }
        File sfDir = new File(rootStorage.getAbsolutePath() + "/soundfonts/");
        if (!sfDir.exists()) {
            sfDir.mkdir();
        }
        updateBuffers(updateRates());
        aRate = Integer.parseInt(prefs.getString("tplusRate",
                Integer.toString(AudioTrack.getNativeOutputSampleRate(AudioTrack.MODE_STREAM))));
        buff = Integer.parseInt(prefs.getString("tplusBuff", "192000")); // This is usually a safe number, but should probably do a test or something
        migrateFrom1X(rootStorage);
        final Editor eee = prefs.edit();
        firstRun = false;
        eee.putBoolean("tplusFirstRun", false);
        eee.putString("dataDir", Environment.getExternalStorageDirectory().getAbsolutePath() + "/TimidityAE/");
        if (new File(dataFolder + "/timidity/timidity.cfg").exists()) {
            if (manConfig = !cfgIsAuto(dataFolder + "/timidity/timidity.cfg")) {
                eee.putBoolean("manConfig", true);
            } else {
                eee.putBoolean("manConfig", false);
                ArrayList<String> soundfonts = new ArrayList<String>();
                FileInputStream fstream = null;
                try {
                    fstream = new FileInputStream(dataFolder + "/timidity/timidity.cfg");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // Get the object of DataInputStream
                DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                //Read File Line By Line
                try {
                    br.readLine(); // skip first line
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String line;
                try {
                    while ((line = br.readLine()) != null) {
                        if (line.indexOf("soundfont \"") >= 0 && line.lastIndexOf('"') >= 0) {
                            try {
                                String st = line.substring(line.indexOf("soundfont \"") + 11,
                                        line.lastIndexOf('"'));
                                soundfonts.add(st);
                            } catch (ArrayIndexOutOfBoundsException e1) {
                                e1.printStackTrace();
                            }

                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    eee.putString("tplusSoundfonts", ObjectSerializer.serialize(soundfonts));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            eee.commit();
            return true;
        } else {
            // Should probably check if 8rock11e exists no matter what
            eee.putBoolean("manConfig", false);

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

                ProgressDialog pd;

                @Override
                protected void onPreExecute() {
                    pd = new ProgressDialog(a);
                    pd.setTitle(a.getResources().getString(R.string.extract));
                    pd.setMessage(a.getResources().getString(R.string.extract_sum));
                    pd.setCancelable(false);
                    pd.setIndeterminate(true);
                    pd.show();
                }

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

                    if (extract8Rock(a) != 777) {
                        Toast.makeText(a, "Could not extrct default soundfont", Toast.LENGTH_SHORT).show();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (pd != null)
                        pd.dismiss();
                    ArrayList<String> tmpConfig = new ArrayList<String>();
                    tmpConfig.add(rootStorage.getAbsolutePath() + "/soundfonts/8Rock11e.sf2");
                    try {
                        eee.putString("tplusSoundfonts", ObjectSerializer.serialize(tmpConfig));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    eee.commit();
                    writeCfg(a, rootStorage.getAbsolutePath() + "/timidity/timidity.cfg", tmpConfig);
                    ((TimidityActivity) a).initCallback();
                }

            };
            task.execute((Void[]) null);
            return false;
        }

    } else {
        return true;
    }
}

From source file:de.schildbach.wallet.data.AddressBookLiveData.java

@Override
public void onLoadComplete(final Loader<Cursor> loader, final Cursor cursor) {
    AsyncTask.execute(new Runnable() {
        @Override/*  w  w  w  .  j av  a  2 s . c o  m*/
        public void run() {
            final Map<String, String> addressBook = new LinkedHashMap<>(cursor.getCount());
            while (cursor.moveToNext()) {
                final String address = cursor
                        .getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_ADDRESS));
                final String label = cursor
                        .getString(cursor.getColumnIndexOrThrow(AddressBookProvider.KEY_LABEL));
                addressBook.put(address, label);
            }
            postValue(addressBook);
        }
    });
}