Code example for ListFragment

Methods: getActivity, onOptionsItemSelected

0
            menu.add(Menu.NONE, POPULATE_ID, 0, "Populate");
            menu.add(Menu.NONE, CLEAR_ID, 0, "Clear");
        } 
 
        @Override public boolean onOptionsItemSelected(MenuItem item) {
            final ContentResolver cr = getActivity().getContentResolver();
 
            switch (item.getItemId()) {
                case POPULATE_ID:
                    if (mPopulatingTask != null) {
                        mPopulatingTask.cancel(false);
                    } 
                    mPopulatingTask = new AsyncTask<Void, Void, Void>() {
                        @Override protected Void doInBackground(Void... params) {
                            for (char c='Z'; c>='A'; c--) {
                                if (isCancelled()) {
                                    break; 
                                } 
                                StringBuilder builder = new StringBuilder("Data ");
                                builder.append(c);
                                ContentValues values = new ContentValues();
                                values.put(MainTable.COLUMN_NAME_DATA, builder.toString());
                                cr.insert(MainTable.CONTENT_URI, values);
                                // Wait a bit between each insert. 
                                try { 
                                    Thread.sleep(250);
                                } catch (InterruptedException e) {
                                } 
                            } 
                            return null; 
                        } 
                    }; 
                    mPopulatingTask.execute((Void[])null);
                    return true; 
 
                case CLEAR_ID:
                    if (mPopulatingTask != null) {
                        mPopulatingTask.cancel(false);
                        mPopulatingTask = null;
                    } 
                    AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
                        @Override protected Void doInBackground(Void... params) {
                            cr.delete(MainTable.CONTENT_URI, null, null);
                            return null; 
                        } 
                    }; 
                    task.execute((Void[])null);
                    return true; 
 
                default: 
                    return super.onOptionsItemSelected(item);
            } 
        } 
 
        @Override public void onListItemClick(ListView l, View v, int position, long id) {
            // Insert desired behavior here.