Example usage for java.util ArrayList remove

List of usage examples for java.util ArrayList remove

Introduction

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

Prototype

public boolean remove(Object o) 

Source Link

Document

Removes the first occurrence of the specified element from this list, if it is present.

Usage

From source file:de.ub0r.android.callmeter.ui.prefs.PreferencesPlain.java

private void loadRules() {
    new AsyncTask<Void, Void, JSONObject>() {
        @Override//from   www  . j a  v a2  s  .  c  o  m
        protected JSONObject doInBackground(final Void... params) {
            try {
                String l;
                StringBuilder sb = new StringBuilder();

                File f = new File(PreferencesPlain.this.getCacheDir(), "ub0rrules.json");
                if (f.exists() && f.lastModified() + CACHE_TIMEOUT > System.currentTimeMillis()) {
                    Log.i(TAG, "found cached data: " + f.getAbsolutePath());
                    BufferedReader r = new BufferedReader(new FileReader(f));
                    while ((l = r.readLine()) != null) {
                        sb.append(l);
                    }
                    r.close();
                }
                if (sb.length() == 0) {
                    if (f.exists()) {
                        f.delete();
                    }
                    HttpURLConnection c = (HttpURLConnection) new URL(
                            "http://ub0r.de/android/callmeter/rulesets/rulesets.json").openConnection();
                    Log.i(TAG, "load new data: " + c.getURL());
                    BufferedReader r = new BufferedReader(new InputStreamReader(c.getInputStream()));
                    FileWriter w = new FileWriter(f);
                    while ((l = r.readLine()) != null) {
                        sb.append(l);
                        w.write(l);
                    }
                    r.close();
                    w.close();
                }
                try {
                    return new JSONObject(sb.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "JSON Error", e);
                    Log.e(TAG, "JSON: " + sb.toString());
                    return null;
                }
            } catch (IOException e) {
                Log.e(TAG, "IOError", e);
            }
            return null;
        }

        @SuppressWarnings({ "deprecation", "rawtypes" })
        @Override
        protected void onPostExecute(final JSONObject result) {
            if (result == null) {
                Toast.makeText(PreferencesPlain.this, R.string.err_export_read, Toast.LENGTH_LONG).show();
                return;
            }
            PreferenceGroup base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_users");
            PreferenceManager pm = base.getPreferenceManager();
            // delete old
            base.removeAll();
            base = (PreferenceGroup) PreferencesPlain.this.findPreference("import_rules_base");
            // build list
            ArrayList<String> keys = new ArrayList<String>(result.length());

            Iterator it = result.keys();
            while (it.hasNext()) {
                keys.add(it.next().toString());
            }
            Collections.sort(keys);
            keys.remove("common");
            keys.add(0, "common");

            OnPreferenceClickListener opcl = new OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(final Preference preference) {
                    Intent intent = new Intent(PreferencesPlain.this, PreferencesRules.class);
                    intent.putExtra(PreferencesRules.EXTRA_JSON, result.toString());
                    intent.putExtra(PreferencesRules.EXTRA_COUNTRY, preference.getKey());
                    PreferencesPlain.this.startActivity(intent);
                    return true;
                }
            };

            for (String k : keys) {
                PreferenceScreen p = pm.createPreferenceScreen(PreferencesPlain.this);
                p.setPersistent(false);
                p.setKey(k);
                p.setTitle(k);
                p.setOnPreferenceClickListener(opcl);
                base.addPreference(p);
            }
        }

        ;
    }.execute((Void) null);
}

From source file:at.the.gogo.panoramio.panoviewer.ImageManager.java

/**
 * Called when something changes in our data set. Cleans up any weak
 * references that are no longer valid along the way.
 *///from  w  w w  .j a v a  2s  .com
private void notifyObservers() {
    final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
    final int count = observers.size();
    for (int i = count - 1; i >= 0; i--) {
        final WeakReference<DataSetObserver> weak = observers.get(i);
        final DataSetObserver obs = weak.get();
        if (obs != null) {
            obs.onChanged();
        } else {
            observers.remove(i);
        }
    }

}

From source file:com.entertailion.android.slideshow.images.ImageManager.java

/**
 * Called when something changes in our data set. Cleans up any weak
 * references that are no longer valid along the way.
 *///ww  w . j av  a2s  . c  o m
public void notifyObservers() {
    Log.d(LOG_TAG, "notifyObservers: " + loading);
    if (loading) {
        final ArrayList<WeakReference<DataSetObserver>> observers = dataSetObservers;
        final int count = observers.size();
        for (int i = count - 1; i >= 0; i--) {
            final WeakReference<DataSetObserver> weak = observers.get(i);
            final DataSetObserver obs = weak.get();
            if (obs != null) {
                obs.onChanged();
            } else {
                observers.remove(i);
            }
        }
    }
}

From source file:com.entertailion.android.slideshow.images.ImageManager.java

/**
 * Called when something changes in our data set. Cleans up any weak
 * references that are no longer valid along the way.
 *//*  w ww  . java2s  .com*/
public void notifyInvalidateObservers() {
    Log.d(LOG_TAG, "notifyInvalidateObservers: " + loading);
    if (loading) {
        final ArrayList<WeakReference<DataSetObserver>> observers = dataSetObservers;
        final int count = observers.size();
        for (int i = count - 1; i >= 0; i--) {
            final WeakReference<DataSetObserver> weak = observers.get(i);
            final DataSetObserver obs = weak.get();
            if (obs != null) {
                obs.onInvalidated();
            } else {
                observers.remove(i);
            }
        }
    }
}

From source file:Game.InteractionCase.java

public boolean process(Card c, String id) {
    if (reaction_only) {
        if (c.is_block()) {
            selectedSpecials.add(c);//from   w  w w.  j a v a 2  s  .co  m
            selectedIds.add(id);
            return true;
        } else
            return false;
    }

    String name = c.getName();
    int cost = c.getCost();
    if ((cost > maximum_cost) || (cost < minimum_cost))
        return false;
    if (selectedSpecials.size() >= maximum_amount)
        return false;
    System.out.println("INCOMING INTERACTIONCASE REQUEST");
    System.out.println("Cardname : " + c.getName() + " - " + "ID: " + id);
    System.out.println("======= ALLOWEDIDS ======");
    for (String s : allowedIds)
        System.out.print(s + " , ");
    System.out.println("=========================");

    if (Character.isDigit(id.charAt(0))) {
        for (String s : selectedIds) {
            if (s.startsWith(id.split("_")[0]))
                return false;
        }
        if (c instanceof ActionCard) {
            if (!action_hand_enabled)
                return false;
        } else if (c instanceof TreasureCard) {
            if (!treasure_hand_enabled)
                return false;
        } else if (c instanceof VictoryCard) {
            if (!victory_hand_enabled)
                return false;
        }
    } else {
        ArrayList<String> nextallowedids = new ArrayList<>();
        nextallowedids.addAll(allowedIds);
        boolean allowed = false;
        for (String s : allowedIds) {
            if (id.startsWith(s)) {
                allowed = true;
                nextallowedids.remove(s);
                break;
            }
        }

        if (c instanceof ActionCard) {
            if (!action_env_enabled)
                return false;
        } else if (c instanceof TreasureCard) {
            if (!treasure_env_enabled)
                return false;
        } else if (c instanceof VictoryCard) {
            if (!victory_env_enabled)
                return false;
        }
        if (!allowed)
            return false;
        else
            allowedIds = nextallowedids;
    }
    System.out.println("INTERACTIONCASE PROCESSING FINISHED.");
    System.out.println("=====  LEAVING CASE WITH ALLOWED IDS: ========");
    for (String s : allowedIds)
        System.out.println(s + " , ");
    System.out.println("===============================================");
    // If this code is reached, all validations have passed, and nothing returned false.
    selectedSpecials.add(c);
    selectedIds.add(id);
    return true;
}

From source file:bot.UniversalBot.java

/**
 * Method which returns cards to exchange.
 * @param hand List of cards.// w w  w .  jav  a2s  .  com
 * @return List of cards to exchange.
 */
public ArrayList<Card> cardsToExchange(ArrayList<Card> hand) {

    ArrayList<Card> cards2Exchange = new ArrayList<Card>(hand);
    System.out.println("[DEBUG] Actual hand: " + hand);
    System.out.println("[DEBUG] Best hand: " + Helpers.bestHand(cards2Exchange));

    ArrayList<Card> cards2Delete = Helpers.bestHand(cards2Exchange);

    for (Card card2Delete : cards2Delete) {
        cards2Exchange.remove(card2Delete);
    }

    return cards2Exchange;

}

From source file:de.ids_mannheim.korap.index.FieldDocument.java

/**
 * Deserialize token stream data./*ww w.j  a v  a2 s  .com*/
 */
public void setData(Map<String, Object> node) {
    this.setPrimaryData((String) node.get("text"));

    String fieldName = (String) node.get("name");

    MultiTermTokenStream mtts = this.newMultiTermTokenStream();

    // Iterate over all tokens in stream
    for (ArrayList<String> token : (ArrayList<ArrayList<String>>) node.get("stream")) {

        try {
            // Initialize MultiTermToken
            MultiTermToken mtt = new MultiTermToken(token.remove(0));

            // Add rest of the list
            for (String term : token) {
                mtt.add(term);
            }
            ;

            // Add MultiTermToken to stream
            mtts.addMultiTermToken(mtt);

        } catch (CorpusDataException cde) {
            this.addError(cde.getErrorCode(), cde.getMessage());
        }
        ;
    }
    ;

    // Add tokenstream to fielddocument
    this.addTV(fieldName, this.getPrimaryData(), mtts);

    // Get foundry info
    if (node.containsKey("foundries"))
        this.setFoundries((String) node.get("foundries"));

    // Get layer info
    if (node.containsKey("layerInfos"))
        this.setLayerInfos((String) node.get("layerInfos"));

    // Get tokenSource info
    if (node.containsKey("tokenSource"))
        this.setTokenSource((String) node.get("tokenSource"));
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {
    final ArrayList<String> infoAndName = new ArrayList<String>();
    try {//from w ww . j  a va 2 s  . c  o  m
        for (int i = 0; i < usersFound.length(); i++) {
            infoAndName.add(usersFound.getJSONObject(i).getString("name"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            Location geoPointLocation = new Location("geoPoint");
            try {
                infoAndName.clear();
                for (int i = 0; i < usersFound.length(); i++) {
                    String appendedText = "";
                    if (!usersFound.getJSONObject(i).has("channel")) {
                        geoPointLocation.setLongitude(usersFound.getJSONObject(i).getDouble("lon"));
                        geoPointLocation.setLatitude(usersFound.getJSONObject(i).getDouble("lat"));
                        float distance = location.distanceTo(geoPointLocation) / 1000;
                        appendedText = String.format("%.1f", distance) + "Km";
                    } else {
                        appendedText = usersFound.getJSONObject(i).getString("channel");
                    }
                    infoAndName.add(appendedText + usersFound.getJSONObject(i).getString("name"));
                    Log.e("infoandname", infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1));
                    Toast.makeText(mContext, infoAndName.toString() + infoAndName.get(0) + infoAndName.get(1),
                            Toast.LENGTH_LONG).show();

                    // infoAndName tem a informacao de distancia ou canal e o nome. Precisa editar
                    //essa parte de baixo pra usar o infoAndName.
                    ArrayList<String> friendsEmails = new ArrayList<>();

                    friendsEmails.addAll(infoAndName);

                    friendsEmails = new ArrayList<>();
                    for (ArrayList<String> array : ServerInformation.getAllActiveListeners()) {
                        friendsEmails.addAll(array);
                        while (friendsEmails.contains(connectedEmail))
                            friendsEmails.remove(connectedEmail);
                    }
                    EmailListAdapter listAdapter = new EmailListAdapter(mContext, R.layout.adapter_email_list,
                            friendsEmails);
                    ListView emails = (ListView) ((Activity) mContext)
                            .findViewById(R.id.gps_friends_from_drawer);
                    emails.setAdapter(listAdapter);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    // Minimum of 2 minutes between checks (120000 milisecs).
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 120000, 0, locationListener);
}

From source file:com.emental.mindraider.core.rest.resource.FolderResource.java

/**
 * Move notebook down in the folder.// w w  w .  j a  v a 2  s  .  c om
 * 
 * @param notebookUri
 *            the notebook uri String
 * @return <code>true</code> if moved, else removed (should be placed into
 *         the next folder)
 * @throws Exception
 *             a generic exception
 */
@SuppressWarnings("unchecked")
public boolean downNotebook(String notebookUri) throws Exception {
    if (notebookUri == null) {
        throw new MindRaiderException("Notebook URI can't be null!");
    }
    // presuming that there exist exactly one notebooks group
    ResourcePropertyGroup[] notebooks = resource.getData()
            .getPropertyGroup(new URI(PROPERTY_GROUP_URI_NOTEBOOKS));
    if (notebooks != null) {
        // search for the notebook URI
        ArrayList<NotebookProperty> arrProperties = notebooks[0].getProperties();
        int i = 0;
        for (NotebookProperty notebookProperty : arrProperties) {
            if (notebookProperty.getUri().toASCIIString().equals(notebookUri)) {
                logger.debug(" Notebook found in properties...");
                if (i < arrProperties.size() - 1) {
                    arrProperties.remove(i);
                    arrProperties.add(i + 1, notebookProperty);
                    notebooks[0].setProperties(arrProperties);
                    return true;
                }
                logger.debug("DELETE!");
                return false;
            }
        }
    } else {
        throw new MindRaiderException("There is no property group!");
    }
    return false;
}

From source file:edu.oregonstate.eecs.mcplan.domains.spbj.SpBjAction.java

@Override
public void doAction(final RandomGenerator rng, final SpBjState s) {
    assert (!done);

    for (int i = 0; i < cat.length; ++i) {
        final SpBjHand h = s.player_hand;
        final ArrayList<Card> cards = h.hands.get(i);
        switch (cat[i]) {
        case Hit:
            assert (!h.passed[i]);
            cards.add(s.deck().deal());/* w w w  . j  a  va 2 s . co m*/
            if (SpBjHand.handValue(cards)[0] >= SpBjHand.busted_score) {
                h.passed[i] = true;
            }
            break;
        case Pass:
            h.passed[i] = true;
            break;
        case Split:
            assert (!h.passed[i]);
            assert (h.canSplit(i));
            final ArrayList<Card> old_hand = h.hands.get(i);
            assert (old_hand.size() == 2);
            assert (old_hand.get(0).rank == old_hand.get(1).rank);
            final ArrayList<Card> new_hand = new ArrayList<Card>();
            final int j = h.Nhands;
            h.Nhands += 1;
            h.children[i] = j;
            h.bets[j] = h.bets[i];
            final Card c = old_hand.remove(1);
            new_hand.add(c);
            h.hands.add(new_hand);
            h.passed[j] = false;
            old_hand.add(s.deck().deal());
            new_hand.add(s.deck().deal());
            break;
        case Double:
            assert (!h.passed[i]);
            assert (h.canDouble(i));
            h.bets[i] *= 2;
            cards.add(s.deck().deal());
            if (SpBjHand.handValue(cards)[0] >= SpBjHand.busted_score) {
                h.passed[i] = true;
            }
            break;
        }
    }

    if (Fn.all(s.player_hand.passed)) {
        terminal = true;
        completeDealerHand(s);
    }

    done = true;
}