Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.yoctopuce.YoctoAPI.YCellular.java

/**
 * Returns a list of nearby cellular antennas, as required for quick
 * geolocation of the device. The first cell listed is the serving
 * cell, and the next ones are the neighboor cells reported by the
 * serving cell./*  w ww.j a va 2  s .  c om*/
 *
 * @return a list of YCellRecords.
 */
public ArrayList<YCellRecord> quickCellSurvey() throws YAPI_Exception {
    String moni;
    ArrayList<String> recs = new ArrayList<String>();
    int llen;
    String mccs;
    int mcc;
    String mncs;
    int mnc;
    int lac;
    int cellId;
    String dbms;
    int dbm;
    String tads;
    int tad;
    String oper;
    ArrayList<YCellRecord> res = new ArrayList<YCellRecord>();
    // may throw an exception
    moni = _AT("+CCED=0;#MONI=7;#MONI");
    mccs = (moni).substring(7, 7 + 3);
    if ((mccs).substring(0, 0 + 1).equals("0")) {
        mccs = (mccs).substring(1, 1 + 2);
    }
    if ((mccs).substring(0, 0 + 1).equals("0")) {
        mccs = (mccs).substring(1, 1 + 1);
    }
    mcc = YAPI._atoi(mccs);
    mncs = (moni).substring(11, 11 + 3);
    if ((mncs).substring(2, 2 + 1).equals(",")) {
        mncs = (mncs).substring(0, 0 + 2);
    }
    if ((mncs).substring(0, 0 + 1).equals("0")) {
        mncs = (mncs).substring(1, 1 + (mncs).length() - 1);
    }
    mnc = YAPI._atoi(mncs);
    recs = new ArrayList<String>(Arrays.asList(moni.split("#")));
    // process each line in turn
    res.clear();
    for (String ii : recs) {
        llen = (ii).length() - 2;
        if (llen >= 44) {
            if ((ii).substring(41, 41 + 3).equals("dbm")) {
                lac = Integer.valueOf((ii).substring(16, 16 + 4), 16);
                cellId = Integer.valueOf((ii).substring(23, 23 + 4), 16);
                dbms = (ii).substring(37, 37 + 4);
                if ((dbms).substring(0, 0 + 1).equals(" ")) {
                    dbms = (dbms).substring(1, 1 + 3);
                }
                dbm = YAPI._atoi(dbms);
                if (llen > 66) {
                    tads = (ii).substring(54, 54 + 2);
                    if ((tads).substring(0, 0 + 1).equals(" ")) {
                        tads = (tads).substring(1, 1 + 3);
                    }
                    tad = YAPI._atoi(tads);
                    oper = (ii).substring(66, 66 + llen - 66);
                } else {
                    tad = -1;
                    oper = "";
                }
                if (lac < 65535) {
                    res.add(new YCellRecord(mcc, mnc, lac, cellId, dbm, tad, oper));
                }
            }
        }
    }
    return res;
}

From source file:com.clustercontrol.notify.action.DeleteNotify.java

public int useCheck(String managerName, List<String> notifyIds) {

    int result = Window.OK;
    List<NotifyCheckIdResultInfo> retList = null;
    List<String> notifyGroupIdList = null;

    try {//from   w  w  w  .j av a 2 s. co  m
        NotifyEndpointWrapper wrapper = NotifyEndpointWrapper.getWrapper(managerName);
        retList = wrapper.checkNotifyId(notifyIds);

        for (NotifyCheckIdResultInfo checkResult : retList) {
            notifyGroupIdList = checkResult.getNotifyGroupIdList();

            if (notifyGroupIdList.size() != 0) {
                String message = null;
                String notifyGroupId = null;
                String[] strings = null;
                String moduleName = "";
                ArrayList<String> checkList = new ArrayList<String>(); // ?????ID??????
                String id = this.toString();

                Iterator<String> itr = notifyGroupIdList.iterator();

                String[] args = { checkResult.getNotifyId() };
                MultiStatus mStatus = new MultiStatus(this.toString(), IStatus.OK,
                        Messages.getString("message.notify.26", args), null);
                IStatus status = null;

                while (itr.hasNext()) {
                    notifyGroupId = itr.next();
                    strings = notifyGroupId.split("-");

                    // HinemosModuleConstant?????
                    if (HinemosModuleConstant.isExist(strings[0])
                            && !strings[0].equals(HinemosModuleConstant.JOB_SESSION)) { // JobSessionID

                        // ?????????????
                        if (!moduleName.equals(strings[0])) {

                            // ???
                            if (!moduleName.equals("")) {
                                status = new Status(IStatus.INFO, id, IStatus.OK, "", null);
                                mStatus.add(status);
                            }

                            moduleName = strings[0];
                            message = "[" + HinemosModuleMessage.nameToString(moduleName) + "]";
                            checkList.clear();

                            status = new Status(IStatus.INFO, id, IStatus.OK, message, null);
                            mStatus.add(status);
                        }

                        // ID
                        StringBuffer monitorId = new StringBuffer();
                        monitorId.append(strings[1]);
                        for (int i = 2; i < strings.length - 1; i++) { // strings?????index???????
                            monitorId.append("-" + strings[i]);
                        }

                        String midStr = monitorId.toString();
                        if (!checkList.contains(midStr)) {
                            checkList.add(midStr);

                            //                    message = "  " + strings[1];
                            message = "  " + midStr;
                            status = new Status(IStatus.INFO, id, IStatus.OK, message, null);
                            mStatus.add(status);
                        }
                    }

                }

                // ?????????
                result = ErrorDialog.openError(null, Messages.getString("info"), null, mStatus);

                continue;
            }
        }
    } catch (RuntimeException | HinemosUnknown_Exception | NotifyNotFound_Exception | InvalidRole_Exception
            | InvalidUserPass_Exception e) {
        m_log.warn("useCheck(), " + HinemosMessage.replace(e.getMessage()), e);
        MessageDialog.openError(null, Messages.getString("failed"),
                Messages.getString("message.hinemos.failure.unexpected") + ", "
                        + HinemosMessage.replace(e.getMessage()));
    }

    return result;
}

From source file:com.notepadlite.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//w  w w.j a  v  a 2 s.co  m
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    final ArrayList<String> cab = new ArrayList<>(numOfNotes);

    listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // Respond to clicks on the actions in the CAB
            switch (item.getItemId()) {
            case R.id.action_export:
                mode.finish(); // Action picked, so close the CAB
                listener.exportNote(cab.toArray());
                return true;
            case R.id.action_delete:
                mode.finish(); // Action picked, so close the CAB
                listener.deleteNote(cab.toArray());
                return true;
            default:
                return false;
            }
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            listener.hideFab();

            // Inflate the menu for the CAB
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu, menu);

            // Clear any old values from cab array
            cab.clear();

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            listener.showFab();
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
            // Add/remove filenames to cab array as they are checked/unchecked
            if (checked) {
                if (sortBy.equals("date"))
                    cab.add(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.add(finalListByName[position]);
            } else {
                if (sortBy.equals("date"))
                    cab.remove(finalListByDate[position]);
                if (sortBy.equals("name"))
                    cab.remove(finalListByName[position]);
            }

            // Update the title in CAB
            if (cab.size() == 0)
                mode.setTitle("");
            else
                mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }
    });

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}

From source file:com.example.administrator.myapplication2._5_Group._5_Group.RightFragment.java

public void showGroupsPosition() {

    HashMap<String, String> tmpmap = new HashMap<>();

    ArrayList<MarkerOptions> arrayMarker = new ArrayList<>();

    if (listItem.size() >= 0) {

        map.clear(); //(1/3)

        for (int i = 0; i < listItem.size(); i++) {
            tmpmap = listItem.get(i);//from w ww  .  j  av  a  2s.co m

            if (!tmpmap.get("lat").equals("null")) {
                MarkerOptions marker = new MarkerOptions();//   
                LatLng pos = new LatLng(Double.parseDouble(tmpmap.get("lat")),
                        Double.parseDouble(tmpmap.get("lng")));
                marker.position(pos);
                if (name.equals(tmpmap.get("id"))) {
                    marker.title("?\n");// ?
                    marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_spot));

                } else {
                    try {
                        marker.title("?" + URLDecoder.decode(tmpmap.get("id"), "UTF-8") + "\n");// ?
                        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin_spot2));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                arrayMarker.add(marker);
            }
        }

        for (int i = 0; i < arrayMarker.size(); i++) {
            map.addMarker(arrayMarker.get(i)).showInfoWindow();
        }

        listItem.clear(); //(2/3)
        arrayMarker.clear(); //(3/3)
    }
}

From source file:algorithm.NQueens.java

public void doMain(String[] args) throws InterruptedException, IOException {
    CmdLineParser parser = new CmdLineParser(this);

    try {/*from  w  w  w. jav  a 2  s .  com*/
        /* Parse the arguments */
        parser.parseArgument(args);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        System.err.println("java NQueens [options...] arguments...");
        parser.printUsage(System.err);

        /* Print program sample showing all of the options */
        System.err.println("\n Example: java NQueens" + parser.printExample(ALL));
        System.exit(1);
    }

    try {
        String resultantPath = "/" + numQueens + "_q" + "/";
        if (mutation == null) {
            resultantPath += "variable/";
        } else {
            resultantPath += mutation.toString() + "/";
        }

        outputDir += resultantPath;

        File dir = new File(outputDir);
        File figureDir = new File(outputDir + "/figures/");
        /* 
         * Returns true if all the directories are created
         * Returns false and the directories may have been made
         * (so far returns false every other time and it works every time)
         */
        dir.mkdirs();
        figureDir.mkdirs();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    for (int count = 0; count < numRuns; ++count) {
        /* Create an initial population of uniformly random chromosomes */
        initPopulation();

        /* Initialize the Breed operation */
        if (mutation != null) {
            Breed.init(new Random(), mutation);
        } else {
            Breed.init(new Random());
        }

        /* Iterate until all of the solutions for the N queens problem has been found */
        while (solutions.size() < distinctSolutions[numQueens - 1] && numGenerations <= maxGenerations) {
            /* If the percentage of similar chromosomes due to in-breeding exceeds
             * the minimum threshold value, increase the amount of mutation
             */
            curSimilarity = similarChromosomes(population);
            if (mutation == null) {
                if (curSimilarity >= inbreedingThreshold) {
                    Breed.inBreeding(true);
                } else {
                    Breed.inBreeding(false);
                }
            }

            /* Calculate the fitness distribution of the current population */
            HashMap<Chromosome, Double> fitness = Fitness.calculate(population);

            /* Instantiate the selection iterator using the fitness distribution,
             * the selection iterator uses roulette wheel selection to select
             * each chromosome.
             */
            Selection selection = new Selection(new Random());
            selection.init(fitness);

            /* Generate the next population by selecting chromosomes from the current
             * population using selection iterator and applying the cloning, crossover,
             * and mutation operations.
             */
            ArrayList<Chromosome> nextPopulation = new ArrayList<Chromosome>(populationSize);
            ArrayList<Chromosome> chromosomes = new ArrayList<Chromosome>(2);

            while (nextPopulation.size() < populationSize) {
                /* Select a random number and apply the breeding operation */
                Integer randomNum = random.nextInt(100);

                /* Pair of parent chromosomes continue on to the next generation.*/
                if (Breed.CLONING.contains(randomNum)) {
                    chromosomes.addAll(Breed.cloning(selection));
                }
                /* Pair of parent chromosomes are cross-overed to create new pair */
                else if (Breed.CROSSOVER.contains(randomNum)) {
                    chromosomes.addAll(Breed.crossover(selection));
                }

                /* Apply the background mutation operator to the chromosomes */
                for (Chromosome chromosome : chromosomes) {
                    randomNum = random.nextInt(100);

                    if (Breed.MUTATION.contains(randomNum)) {
                        nextPopulation.add(Breed.mutation(chromosome));
                    } else {
                        nextPopulation.add(chromosome);
                    }
                }
                chromosomes.clear();
            }

            /* If there are any solutions (fitness of 1) that are unique save them */
            for (Chromosome chromosome : fitness.keySet()) {
                if (fitness.get(chromosome) == 1.0) {
                    if (uniqueSolution(chromosome)) {
                        /* Save a copy of the chromosome */
                        Chromosome solution = new Chromosome(new ArrayList<Integer>(chromosome.get()),
                                chromosome.size());
                        solutions.add(solution);
                        solutionGeneration.put(solutions.size(), numGenerations);

                        /* Perform three rotations then a reflection followed by three more rotations */
                        for (int i = 0; i < 6; ++i) {
                            rotation = Transformation.rotate(solutions.get(solutions.size() - 1));

                            if (uniqueSolution(rotation)) {
                                solutions.add(rotation);
                                solutionGeneration.put(solutions.size(), numGenerations);
                            } else {
                                if (rotationMiss.containsKey(numGenerations)) {
                                    rotationMiss.put(numGenerations, rotationMiss.get(numGenerations) + 1);
                                } else {
                                    rotationMiss.put(numGenerations, 1);
                                }
                            }

                            if (i == 2) {
                                reflection = Transformation.reflect(solution);

                                if (uniqueSolution(reflection)) {
                                    solutions.add(reflection);
                                    solutionGeneration.put(solutions.size(), numGenerations);
                                } else {
                                    if (reflectionMiss.containsKey(numGenerations)) {
                                        reflectionMiss.put(numGenerations,
                                                reflectionMiss.get(numGenerations) + 1);
                                    } else {
                                        reflectionMiss.put(numGenerations, 1);
                                    }
                                }
                            }
                        }
                    } else {
                        if (duplicateBuffer.containsKey(numGenerations)) {
                            duplicateBuffer.put(numGenerations, duplicateBuffer.get(numGenerations) + 1);
                        } else {
                            duplicateBuffer.put(numGenerations, 1);
                        }
                    }
                }
            }

            /* Save average fitness for the current generation */
            DescriptiveStatistics descStats = new DescriptiveStatistics(Doubles.toArray(fitness.values()));
            fitnessBuffer.add(descStats.getMean());

            /* Save chromosome similarity and mutation rate for current generation */
            similarityBuffer.add(curSimilarity);

            /* Save the variable mutation rate */
            if (mutation == null) {
                mutationBuffer.add((Breed.MUTATION.upperEndpoint() - Breed.MUTATION.lowerEndpoint()) / 100.0);
            }

            /* Calculate statistics for the fitness, similarity, and mutation buffer every 1000, generations */
            if ((numGenerations % 1000) == 0) {
                calcStatistics(1000);
            }

            /* Write the current results to file every 10,000 generations */
            if ((numGenerations % 10000) == 0) {
                writeResults();
            }

            /* Set the current population as the NEXT population */
            fitness.clear();
            population = nextPopulation;

            ++numGenerations;
        }

        /* Calculate statistics and write any remaining results */
        if (fitnessBuffer.size() > 0) {
            calcStatistics(1000);
        }
        writeResults();

        /* Display random solutions for the number of solutions specified */
        for (int j = 0; j < numDisplay; ++j) {
            /* Display a random solution */
            Chromosome solution = solutions.get(random.nextInt(solutions.size()));

            try {
                QueenGame myGame = new QueenGame(new QueenBoard(Ints.toArray(solution.get()), numQueens));
                myGame.playGame(
                        outputDir + "/figures/" + "figure_run_" + String.valueOf(runNumber) + "_" + j + ".png");
            } catch (Exception e) {
                System.out.println("Bad set of Queens");
            }
        }

        /* Reset the current state for the next run and increment run number */
        reset();
        ++runNumber;
    }
}

From source file:com.android.exchange.adapter.EmailSyncAdapter.java

/**
            * Serialize commands to delete items from the server; as we find items to delete, add their
            * id's to the deletedId's array
            *// www .  ja  va2 s.c  om
            * @param s the Serializer we're using to create post data
            * @param deletedIds ids whose deletions are being sent to the server
            * @param first whether or not this is the first command being sent
            * @return true if SYNC_COMMANDS hasn't been sent (false otherwise)
            * @throws IOException
            */
@VisibleForTesting
boolean sendDeletedItems(Serializer s, ArrayList<Long> deletedIds, boolean first) throws IOException {
    ContentResolver cr = mContext.getContentResolver();

    // Find any of our deleted items
    Cursor c = cr.query(Message.DELETED_CONTENT_URI, Message.LIST_PROJECTION,
            MessageColumns.MAILBOX_KEY + '=' + mMailbox.mId, null, null);
    // We keep track of the list of deleted item id's so that we can remove them from the
    // deleted table after the server receives our command
    deletedIds.clear();
    try {
        while (c.moveToNext()) {
            String serverId = c.getString(Message.LIST_SERVER_ID_COLUMN);
            // Keep going if there's no serverId
            if (serverId == null) {
                continue;
                // Also check if this message is referenced elsewhere
            } else if (messageReferenced(cr, c.getLong(Message.CONTENT_ID_COLUMN))) {
                userLog("Postponing deletion of referenced message: ", serverId);
                continue;
            } else if (first) {
                s.start(Tags.SYNC_COMMANDS);
                first = false;
            }
            // Send the command to delete this message
            s.start(Tags.SYNC_DELETE).data(Tags.SYNC_SERVER_ID, serverId).end();
            deletedIds.add(c.getLong(Message.LIST_ID_COLUMN));
        }
    } finally {
        c.close();
    }

    return first;
}

From source file:com.miz.mizuu.fragments.ShowSeasonsFragment.java

private void addWatched(boolean hasWatched) {
    int tempCount = 0;

    ArrayList<TvShowEpisode> tempEpisodes = new ArrayList<TvShowEpisode>(allEpisodes);

    for (int i = 0; i < tempEpisodes.size(); i++) {
        if (tempEpisodes.get(i).hasWatched() == hasWatched) {
            if (seasonEpisodeCount.get(Integer.valueOf(tempEpisodes.get(i).getSeason())) == 0) {
                seasonEpisodeCount.append(Integer.valueOf(tempEpisodes.get(i).getSeason()), 1);
                seasons.add(tempEpisodes.get(i).getSeason());
            } else {
                tempCount = seasonEpisodeCount.get(Integer.valueOf(tempEpisodes.get(i).getSeason()));
                seasonEpisodeCount.append(Integer.valueOf(tempEpisodes.get(i).getSeason()), tempCount + 1);
            }/*from w w  w  . j  a va 2 s  .  c  om*/
            shownEpisodes.add(tempEpisodes.get(i));
        }
    }

    tempEpisodes.clear();
    tempEpisodes = null;
}

From source file:com.geotrackin.gpslogger.GpsMainActivity.java

/**
 * Allows user to send a GPX/KML file along with location, or location only
 * using a provider. 'Provider' means any application that can accept such
 * an intent (Facebook, SMS, Twitter, Email, K-9, Bluetooth)
 *//*www. j a v a  2s .  c  o m*/
private void Share() {
    tracer.debug("GpsMainActivity.Share");
    try {

        final String locationOnly = getString(R.string.sharing_location_only);
        final File gpxFolder = new File(AppSettings.getGpsLoggerFolder());
        if (gpxFolder.exists()) {

            File[] enumeratedFiles = Utilities.GetFilesInFolder(gpxFolder);

            Arrays.sort(enumeratedFiles, new Comparator<File>() {
                public int compare(File f1, File f2) {
                    return -1 * Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
                }
            });

            List<String> fileList = new ArrayList<String>(enumeratedFiles.length);

            for (File f : enumeratedFiles) {
                fileList.add(f.getName());
            }

            fileList.add(0, locationOnly);
            final String[] files = fileList.toArray(new String[fileList.size()]);

            final ArrayList selectedItems = new ArrayList(); // Where we track the selected items

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            // Set the dialog title
            builder.setTitle(R.string.osm_pick_file)
                    .setMultiChoiceItems(files, null, new DialogInterface.OnMultiChoiceClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                            if (isChecked) {

                                if (which == 0) {
                                    //Unselect all others
                                    ((AlertDialog) dialog).getListView().clearChoices();
                                    ((AlertDialog) dialog).getListView().setItemChecked(which, isChecked);
                                    selectedItems.clear();
                                } else {
                                    //Unselect the settings item
                                    ((AlertDialog) dialog).getListView().setItemChecked(0, false);
                                    if (selectedItems.contains(0)) {
                                        selectedItems.remove(selectedItems.indexOf(0));
                                    }
                                }

                                selectedItems.add(which);
                            } else if (selectedItems.contains(which)) {
                                // Else, if the item is already in the array, remove it
                                selectedItems.remove(Integer.valueOf(which));
                            }
                        }
                    }).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {

                            if (selectedItems.size() <= 0) {
                                return;
                            }

                            final Intent intent = new Intent(Intent.ACTION_SEND);
                            intent.setType("*/*");

                            if (selectedItems.get(0).equals(0)) {

                                tracer.debug("User selected location only");
                                intent.setType("text/plain");

                                intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.sharing_mylocation));
                                if (Session.hasValidLocation()) {
                                    String bodyText = getString(R.string.sharing_googlemaps_link,
                                            String.valueOf(Session.getCurrentLatitude()),
                                            String.valueOf(Session.getCurrentLongitude()));
                                    intent.putExtra(Intent.EXTRA_TEXT, bodyText);
                                    intent.putExtra("sms_body", bodyText);
                                    startActivity(
                                            Intent.createChooser(intent, getString(R.string.sharing_via)));
                                }

                            } else {
                                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                                intent.putExtra(Intent.EXTRA_SUBJECT,
                                        "Geotrackin (Android app): Here are some files.");
                                intent.setType("*/*");

                                ArrayList<Uri> chosenFiles = new ArrayList<Uri>();

                                for (Object path : selectedItems) {
                                    File file = new File(gpxFolder, files[Integer.valueOf(path.toString())]);
                                    Uri uri = Uri.fromFile(file);
                                    chosenFiles.add(uri);
                                }

                                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, chosenFiles);
                                startActivity(Intent.createChooser(intent, getString(R.string.sharing_via)));
                            }
                        }
                    }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            selectedItems.clear();
                        }
                    });

            builder.create();
            builder.show();

        } else {
            Utilities.MsgBox(getString(R.string.sorry), getString(R.string.no_files_found), this);
        }
    } catch (Exception ex) {
        tracer.error("Share", ex);
    }

}

From source file:com.anjalimacwan.fragment.NoteListFragment.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void listNotes() {
    // Get number of files
    int numOfFiles = getNumOfNotes(getActivity().getFilesDir());
    int numOfNotes = numOfFiles;

    // Get array of file names
    String[] listOfFiles = getListOfNotes(getActivity().getFilesDir());
    ArrayList<String> listOfNotes = new ArrayList<>();

    // Remove any files from the list that aren't notes
    for (int i = 0; i < numOfFiles; i++) {
        if (NumberUtils.isNumber(listOfFiles[i]))
            listOfNotes.add(listOfFiles[i]);
        else//from   ww w .  j a va 2 s . c om
            numOfNotes--;
    }

    // Declare ListView
    final ListView listView = (ListView) getActivity().findViewById(R.id.listView1);

    // Create arrays of note lists
    String[] listOfNotesByDate = new String[numOfNotes];
    String[] listOfNotesByName = new String[numOfNotes];

    NoteListItem[] listOfTitlesByDate = new NoteListItem[numOfNotes];
    NoteListItem[] listOfTitlesByName = new NoteListItem[numOfNotes];

    ArrayList<NoteListItem> list = new ArrayList<>(numOfNotes);

    for (int i = 0; i < numOfNotes; i++) {
        listOfNotesByDate[i] = listOfNotes.get(i);
    }

    // If sort-by is "by date", sort in reverse order
    if (sortBy.equals("date"))
        Arrays.sort(listOfNotesByDate, Collections.reverseOrder());

    // Get array of first lines of each note
    for (int i = 0; i < numOfNotes; i++) {
        try {
            String title = listener.loadNoteTitle(listOfNotesByDate[i]);
            String date = listener.loadNoteDate(listOfNotesByDate[i]);
            listOfTitlesByDate[i] = new NoteListItem(title, date);
        } catch (IOException e) {
            showToast(R.string.error_loading_list);
        }
    }

    // If sort-by is "by name", sort alphabetically
    if (sortBy.equals("name")) {
        // Copy titles array
        System.arraycopy(listOfTitlesByDate, 0, listOfTitlesByName, 0, numOfNotes);

        // Sort titles
        Arrays.sort(listOfTitlesByName, NoteListItem.NoteComparatorTitle);

        // Initialize notes array
        for (int i = 0; i < numOfNotes; i++)
            listOfNotesByName[i] = "new";

        // Copy filenames array with new sort order of titles and nullify date arrays
        for (int i = 0; i < numOfNotes; i++) {
            for (int j = 0; j < numOfNotes; j++) {
                if (listOfTitlesByName[i].getNote().equals(listOfTitlesByDate[j].getNote())
                        && listOfNotesByName[i].equals("new")) {
                    listOfNotesByName[i] = listOfNotesByDate[j];
                    listOfNotesByDate[j] = "";
                    listOfTitlesByDate[j] = new NoteListItem("", "");
                }
            }
        }

        // Populate ArrayList with notes, showing name as first line of the notes
        list.addAll(Arrays.asList(listOfTitlesByName));
    } else if (sortBy.equals("date"))
        list.addAll(Arrays.asList(listOfTitlesByDate));

    // Create the custom adapters to bind the array to the ListView
    final NoteListDateAdapter dateAdapter = new NoteListDateAdapter(getActivity(), list);
    final NoteListAdapter adapter = new NoteListAdapter(getActivity(), list);

    // Display the ListView
    if (showDate)
        listView.setAdapter(dateAdapter);
    else
        listView.setAdapter(adapter);

    // Finalize arrays to prepare for handling clicked items
    final String[] finalListByDate = listOfNotesByDate;
    final String[] finalListByName = listOfNotesByName;

    // Make ListView handle clicked items
    listView.setClickable(true);
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
            if (sortBy.equals("date")) {
                if (directEdit)
                    listener.editNote(finalListByDate[position]);
                else
                    listener.viewNote(finalListByDate[position]);
            } else if (sortBy.equals("name")) {
                if (directEdit)
                    listener.editNote(finalListByName[position]);
                else
                    listener.viewNote(finalListByName[position]);
            }
        }
    });

    // Make ListView handle contextual action bar
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        final ArrayList<String> cab = new ArrayList<>(numOfNotes);

        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

            @Override
            public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                // Respond to clicks on the actions in the CAB
                switch (item.getItemId()) {
                case R.id.action_export:
                    mode.finish(); // Action picked, so close the CAB
                    listener.exportNote(cab.toArray());
                    return true;
                case R.id.action_delete:
                    mode.finish(); // Action picked, so close the CAB
                    listener.deleteNote(cab.toArray());
                    return true;
                default:
                    return false;
                }
            }

            @Override
            public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                listener.hideFab();

                // Inflate the menu for the CAB
                MenuInflater inflater = mode.getMenuInflater();
                inflater.inflate(R.menu.context_menu, menu);

                // Clear any old values from cab array
                cab.clear();

                return true;
            }

            @Override
            public void onDestroyActionMode(ActionMode mode) {
                listener.showFab();
            }

            @Override
            public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
                // Add/remove filenames to cab array as they are checked/unchecked
                if (checked) {
                    if (sortBy.equals("date"))
                        cab.add(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.add(finalListByName[position]);
                } else {
                    if (sortBy.equals("date"))
                        cab.remove(finalListByDate[position]);
                    if (sortBy.equals("name"))
                        cab.remove(finalListByName[position]);
                }

                // Update the title in CAB
                if (cab.size() == 0)
                    mode.setTitle("");
                else
                    mode.setTitle(cab.size() + " " + listener.getCabString(cab.size()));
            }

            @Override
            public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                return false;
            }
        });
    }

    // If there are no saved notes, then display the empty view
    if (numOfNotes == 0) {
        TextView empty = (TextView) getActivity().findViewById(R.id.empty);
        listView.setEmptyView(empty);
    }
}