Example usage for java.util ArrayList set

List of usage examples for java.util ArrayList set

Introduction

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

Prototype

public E set(int index, E element) 

Source Link

Document

Replaces the element at the specified position in this list with the specified element.

Usage

From source file:com.clustercontrol.notify.composite.NotifyListComposite.java

/**
 * ?????//w w  w  . ja va  2s  .c om
 *
 * @see com.clustercontrol.notify.action.GetNotifyTableDefineCheckBox#get()
 * @see #update()
 */
private void initialize() {
    GridLayout layout = new GridLayout(1, true);
    this.setLayout(layout);
    layout.marginHeight = 0;
    layout.marginWidth = 0;

    final Table table = new Table(this, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION);
    WidgetTestUtil.setTestId(this, null, table);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);

    GridData gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    table.setLayoutData(gridData);

    // ??
    this.tableViewer = new CommonTableViewer(table);

    if (this.isSelect) {
        this.tableViewer.createTableColumn(GetNotifyTableDefineCheckBox.get(),
                GetNotifyTableDefineCheckBox.SORT_COLUMN_INDEX, GetNotifyTableDefineCheckBox.SORT_ORDER);
    } else {
        this.tableViewer.createTableColumn(GetNotifyTableDefineNoCheckBox.get(),
                GetNotifyTableDefineNoCheckBox.SORT_COLUMN_INDEX1,
                GetNotifyTableDefineNoCheckBox.SORT_COLUMN_INDEX2, GetNotifyTableDefineNoCheckBox.SORT_ORDER);
        // ???????????????
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.getColumn(i).setMoveable(true);
        }

        // ?
        this.tableViewer.addDoubleClickListener(new NotifyDoubleClickListener(this));
    }
    if (this.isSelect) {

        /**???*/
        table.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {

                //???TableColumn????
                TableItem[] ti = table.getSelection();
                for (int i = 0; i < ti.length; i++) {
                    @SuppressWarnings("unchecked")
                    ArrayList<Object> al = (ArrayList<Object>) ti[i].getData();
                    WidgetTestUtil.setTestId(this, "tableitem" + i, ti[i]);
                    if ((Boolean) al.get(0)) {
                        //YES?NO
                        al.set(GetNotifyTableDefineCheckBox.SELECTION, false);
                    } else {
                        //NO?YES
                        al.set(GetNotifyTableDefineCheckBox.SELECTION, true);

                    }
                }
                //????????
                tableViewer.refresh();
            }
        });
    } else {
        // ???
        this.totalLabel = new Label(this, SWT.RIGHT);
        WidgetTestUtil.setTestId(this, "total", totalLabel);
        gridData = new GridData();
        gridData.horizontalAlignment = GridData.FILL;
        gridData.verticalAlignment = GridData.FILL;
        this.totalLabel.setLayoutData(gridData);
    }

}

From source file:com.google.android.apps.dashclock.ExtensionManager.java

public List<ExtensionWithData> getInternalActiveExtensionsWithData() {
    // Extract the data from the all active extension cache
    List<ComponentName> internalActiveExtensions = getInternalActiveExtensionNames();
    ArrayList<ExtensionWithData> activeExtensions = new ArrayList<>(
            Arrays.asList(new ExtensionWithData[internalActiveExtensions.size()]));
    synchronized (mActiveExtensions) {
        for (ExtensionWithData ewd : mActiveExtensions) {
            int pos = internalActiveExtensions.indexOf(ewd.listing.componentName());
            if (pos >= 0) {
                activeExtensions.set(pos, ewd);
            }/*from   w  w  w  .ja  v a  2s.c  om*/
        }
    }

    // Clean any null/unset data
    int count = activeExtensions.size();
    for (int i = count - 1; i >= 0; i--) {
        if (activeExtensions.get(i) == null) {
            activeExtensions.remove(i);
        }
    }
    return activeExtensions;
}

From source file:org.openmeetings.app.remote.ChatService.java

/**
 * sends a Chat-Message/*from   w  ww . java 2s  .co  m*/
 * to all members of the Chatroom
 * and all additional users (waitng for a free entry for example)
 * @param newMessage
 * @return
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public int sendMessageWithClient(Object newMessage) {
    try {
        IConnection current = Red5.getConnectionLocal();
        RoomClient currentClient = this.clientListManager.getClientByStreamId(current.getClient().getId());
        Long room_id = currentClient.getRoom_id();

        log.debug("room_id: " + room_id);
        log.debug("currentClient.getIsChatNotification(): " + currentClient.getIsChatNotification());
        if (currentClient.getIsChatNotification()) {
            room_id = currentClient.getChatUserRoomId();
        }

        //log.error(newMessage.getClass().getName());
        ArrayList messageMap = (ArrayList) newMessage;
        //adding delimiter space, cause otherwise an emoticon in the last string would not be found
        String messageText = messageMap.get(4).toString() + " ";
        //log.error("messageText"+messageText);
        //add server time
        messageMap.set(1, parseDateAsTimeString());
        LinkedList<String[]> parsedStringObjects = ChatString.getInstance().parseChatString(messageText);
        //log.error("parsedStringObjects"+parsedStringObjects.size());
        log.debug("size:" + messageMap.size());
        messageMap.add(parsedStringObjects);
        newMessage = messageMap;

        HashMap<String, Object> hsm = new HashMap<String, Object>();
        hsm.put("client", currentClient);
        hsm.put("message", newMessage);

        List<HashMap<String, Object>> myChatList = myChats.get(room_id);
        if (myChatList == null)
            myChatList = new LinkedList<HashMap<String, Object>>();

        if (myChatList.size() == chatRoomHistory)
            myChatList.remove(0);
        myChatList.add(hsm);
        myChats.put(room_id, myChatList);

        log.debug("SET CHATROOM: " + room_id);

        //broadcast to everybody in the room/domain
        Collection<Set<IConnection>> conCollection = current.getScope().getConnections();
        for (Set<IConnection> conset : conCollection) {
            for (IConnection conn : conset) {
                if (conn != null) {
                    if (conn instanceof IServiceCapableConnection) {

                        RoomClient rcl = this.clientListManager.getClientByStreamId(conn.getClient().getId());

                        if (rcl == null) {
                            continue;
                        }
                        if (rcl.getIsAVClient()) {
                            continue;
                        }
                        if (rcl.getIsScreenClient() != null && rcl.getIsScreenClient()) {
                            continue;
                        }

                        log.debug("*..*idremote room_id: " + room_id);
                        log.debug("*..*my idstreamid room_id: " + rcl.getRoom_id());
                        if (room_id != null && room_id.equals(rcl.getRoom_id())) {
                            ((IServiceCapableConnection) conn).invoke("sendVarsToMessageWithClient",
                                    new Object[] { hsm }, this);
                            log.debug("sending sendVarsToMessageWithClient to " + conn);
                        } else if (rcl.getIsChatNotification()) {
                            if (room_id.equals(rcl.getChatUserRoomId()) && room_id != null) {
                                ((IServiceCapableConnection) conn).invoke("sendVarsToMessageWithClient",
                                        new Object[] { hsm }, this);
                            }
                        }

                    }
                }
            }
        }

    } catch (Exception err) {
        log.error("[ChatService sendMessageWithClient] ", err);
        return -1;
    }
    return 1;
}

From source file:org.mmadsen.sim.transmissionlab.analysis.IndividualTraitFrequencyAnalyzer.java

private void updateCumTopNResidenceByTrait(List<Integer> curTraitsTopN) {
    int listPos = 0;
    for (Integer trait : curTraitsTopN) {
        if (this.cumTraitTopNResidenceTimes.containsKey(trait)) {
            // Because the ArrayList has been initialized to hold zeros for each trait in each
            // top N list position, if we've seen the trait before in the map we can get on
            // with the business of incrementing a count, whether that count is zero or not.
            Integer count = this.cumTraitTopNResidenceTimes.get(trait).get(listPos);
            count++;//from w  w w.j  av a2  s  . c o  m
            this.cumTraitTopNResidenceTimes.get(trait).set(listPos, count);
        } else {
            // First create a new ArrayList and initialize 0..topNListSize to 0 counts,
            // so all array positions are defined for the upper branch of the "if"
            ArrayList<Integer> traitCountList = new ArrayList<Integer>();
            for (int i = 0; i < this.topNListSize; i++) {
                traitCountList.add(0);
            }

            // now increment the counter for the one trait/list position combo we're dealing with
            traitCountList.set(listPos, 1);
            this.cumTraitTopNResidenceTimes.put(trait, traitCountList);
        }
        listPos++;
    }
}

From source file:com.amaze.carbonfilemanager.fragments.preference_fragments.Preffrag.java

/**
 * Dynamically enables autodisabled shortcuts, and disables inaccessible shortcuts when user
 * changes root access and hidden files visibility preferences.
 */// w  w w.j  av  a  2s .co  m
private void setEnabledShortcuts() {
    ArrayList<String> predigestedPref = TinyDB.getList(sharedPref, String.class, FoldersPref.KEY, null);
    if (predigestedPref == null)
        return;

    ArrayList<FoldersPref.Shortcut> currentValue = castStringListToTrioList(predigestedPref);

    for (int i = 0; i < currentValue.size(); i++) {
        if (FoldersPref.canShortcutTo(currentValue.get(i).directory, sharedPref)
                && currentValue.get(i).autodisabled) {
            FoldersPref.Shortcut shortcut = new FoldersPref.Shortcut(currentValue.get(i).name,
                    currentValue.get(i).directory, FoldersPref.Shortcut.TRUE);
            currentValue.set(i, shortcut);
        } else if (!FoldersPref.canShortcutTo(currentValue.get(i).directory, sharedPref)
                && currentValue.get(i).enabled) {
            FoldersPref.Shortcut shortcut = new FoldersPref.Shortcut(currentValue.get(i).name,
                    currentValue.get(i).directory, FoldersPref.Shortcut.AUTOFALSE);
            currentValue.set(i, shortcut);
        }
    }

    TinyDB.putList(sharedPref, FoldersPref.KEY, FoldersPref.castTrioListToStringList(currentValue));
}

From source file:gr.iit.demokritos.cru.cps.ai.KeyphraseClustering.java

public ArrayList<String> getClusters() throws Exception {
    System.out.println("Clustering......");
    // int[] clusters_size = new int[clusters];
    HierarchicalClusterer cl = new HierarchicalClusterer();
    // EM em=new EM();
    // XMeans xm = new XMeans();       no nominal attributes
    // DBSCAN db= new DBSCAN();        not our distance function
    // CascadeSimpleKMeans c = new CascadeSimpleKMeans(); not our distance function  

    cl.setNumClusters(this.clusters);
    if (language.equals("en")) {
        // cl.setDistanceFunction(wd);
        //xm.setDistanceF(wd);
        cl.setDistanceFunction(wd);/*  ww w .j ava 2s  .  c  o m*/
    } else if (language.equals("de")) {
        cl.setDistanceFunction(wdde);
        //c.setDistanceFunction(wdde);
        //xm.setDistanceF(wdde);
    } else if (language.equals("el")) {
        cl.setDistanceFunction(wdel);
        //c.setDistanceFunction(wdel);
        // xm.setDistanceF(wdel);
    }
    cl.buildClusterer(data);
    //xm.buildClusterer(data);
    //c.setMaxIterations(5);
    ArrayList<String> clustersList = new ArrayList<String>();
    for (int i = 0; i < cl.numberOfClusters(); i++) {
        clustersList.add("");
    }
    //cl.buildClusterer(data);
    //em.buildClusterer(data);
    // xm.buildClusterer(data);

    for (int j = 0; j < data.numInstances(); j++) {
        //double[] prob = c.distributionForInstance(data.instance(j));
        //double[] prob = cl.distributionForInstance(data.instance(j)); 
        String clusterLine = data.instance(j).stringValue(0);

        int clust = cl.clusterInstance(data.instance(j));
        clustersList.set(clust, clustersList.get(clust).concat(clusterLine + ";"));
        //take the probabilities prob[i] that it is in the coresponding cluster i
        /*for (int i = 0; i < prob.length; i++) {
         //keep the cluster that has prob>0.9, as this is the cluster that the word is in
         if (prob[i] > 0.9) {
         //keep for every cluster its terms
         clustersList.set(i, clustersList.get(i).concat(clusterLine + ";"));
         //keep the size of cluster i
         // clusters_size[i] = clusters_size[i] + 1;
         }
         }*/
    }
    return clustersList;
}

From source file:org.ala.spatial.web.services.LayerDistancesWSController.java

private String makeCSV(String type) {
    Map<String, Double> map = LayerDistanceIndex.loadDistances();

    TreeSet<String> layerSet = new TreeSet<String>();
    for (String k : map.keySet()) {
        String[] ks = k.split(" ");
        layerSet.add(ks[0]);//from   ww  w.  j  a  v  a  2 s.c  om
        layerSet.add(ks[1]);
    }
    ArrayList<String> layerList = new ArrayList<String>(layerSet);

    //match against layers
    ArrayList<Layer> layerMatch = new ArrayList<Layer>(layerList.size());
    for (int i = 0; i < layerList.size(); i++) {
        layerMatch.add(null);
    }
    List<Field> fields = Client.getFieldDao().getFields();
    List<Layer> layers = Client.getLayerDao().getLayers();
    for (int i = 0; i < layerList.size(); i++) {
        for (int j = 0; j < fields.size(); j++) {
            if (fields.get(j).getId().equals(layerList.get(i))) {
                for (int k = 0; k < layers.size(); k++) {
                    if ((fields.get(j).getSpid() + "").equals(layers.get(k).getId() + "")) {
                        layerMatch.set(i, layers.get(k));
                        break;
                    }
                }
                break;
            }
        }
    }

    //output lower association matrix
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < layerList.size(); i++) {
        if (i > 0) {
            if (type.equals("name")) {
                sb.append(layerMatch.get(i).getName());
            } else if (type.equals("displayname")) {
                sb.append(layerMatch.get(i).getDisplayname());
            }
        }
        sb.append(",");
        int size = (i == 0) ? layerList.size() - 1 : i;
        for (int j = 0; j < size; j++) {
            if (i == 0) {
                if (type.equals("name")) {
                    sb.append(layerMatch.get(j).getName());
                } else if (type.equals("displayname")) {
                    sb.append(layerMatch.get(j).getDisplayname());
                }
            } else {
                String key = (layerList.get(i).compareTo(layerList.get(j)) < 0)
                        ? layerList.get(i) + " " + layerList.get(j)
                        : layerList.get(j) + " " + layerList.get(i);
                if (key != null && map.get(key) != null) {
                    sb.append(map.get(key));
                }
            }

            if (j < size - 1) {
                sb.append(",");
            }
        }
        sb.append("\n");
    }

    return sb.toString();
}

From source file:com.mythesis.userbehaviouranalysis.ProfileAnalysis.java

/**
 * finds the profiles that match user's interests given his web history
 * @param userID the user's id/*  w ww  . ja v a 2 s  . c o m*/
 * @param history the user's web history
 * @param input a txt file that contains the necessary parameters
 */
public void perform(String userID, String[] history, File input) {

    System.out.println("total urls = " + history.length);
    //default parameters
    //number of random queries for each profile
    int numQueriesSuggestion = 5;
    //number of random webpages per query to suggest - total number of suggestions = 
    // numQueriesSuggestion*pagesPerQuerySuggestion
    int pagesPerQuerySuggestion = 1;
    //number of random queries to return as examples for alternatives profiles
    int numQueriesExample = 2;

    //we get the current date/time
    DateTime current = new DateTime();
    DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
    String timestamp = fmt.print(current);

    //update user info - i'll store the results when i'll perform the last analysis
    Mongo mongo = new Mongo("localhost", 27017);
    DB db = mongo.getDB("profileAnalysis");
    DBCollection userinfo = db.getCollection("userinfo");
    BasicDBObject newDocument = new BasicDBObject();
    newDocument.put("$set", new BasicDBObject().append("timestamp", timestamp));
    BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("userID", userID);
    userinfo.update(searchQuery, newDocument, true, false);

    //read the neccessary parameters
    Utils utils = new Utils();
    utils.readInput(input);
    HashMap<String, ArrayList<String>> wordvectors = utils.wordvectors;
    HashMap<String, String> crawlerOutputPaths = utils.crawlerOutputPaths;

    //get the urls' content
    ArrayList<String> webpages = new ArrayList<>();
    ArrayList<String> urls = new ArrayList<>();
    for (int i = 0; i < history.length; i++) {
        WebParser pageParser = new WebParser(history[i]);
        pageParser.parse();
        String content = pageParser.getContent();
        if ("".equals(content) || content == null)
            continue;
        webpages.add(content);
        urls.add(history[i]);
    }

    //calculate the urls' scores
    HashMap<String, double[]> historyScores = new HashMap<>();
    String[] webpagesArr = new String[webpages.size()];
    webpagesArr = webpages.toArray(webpagesArr);
    String[] urlsArr = new String[urls.size()];
    urlsArr = urls.toArray(urlsArr);
    for (String profile : wordvectors.keySet()) {
        Scorer scorer = new Scorer(webpagesArr, urlsArr, wordvectors.get(profile));
        double[] semanticScores = scorer.getSemanticScores();
        double[] relevanceScores = scorer.getRelevanceScores();
        double[] confidenceScores = scorer.getConfidenceScores();
        double[] scores = scoreFormula(semanticScores, relevanceScores, confidenceScores);
        historyScores.put(profile, scores);
    }

    //find the maximum score of every url and get summation of the scores for each profile
    HashMap<String, Double> userProfilesScore = new HashMap<>();
    for (int i = 0; i < webpages.size(); i++) {
        double max = 0.0;
        String info = "undefined";
        for (String profile : historyScores.keySet()) {
            if (historyScores.get(profile)[i] > max) {
                max = historyScores.get(profile)[i];
                info = profile;
            }
        }
        if (!"undefined".equals(info)) {
            Double prevscore = userProfilesScore.get(info);
            userProfilesScore.put(info, (prevscore == null) ? max : prevscore + max);
        }
    }

    //find which profile level has maximum score e.g. if football/level=0 score is greater
    //than football/level=1 score then the user is better described as a football/level=0 user
    HashMap<String, Double> userProfileScores = new HashMap<>();
    HashMap<String, String> userProfileLevels = new HashMap<>();
    for (String s : userProfilesScore.keySet()) {
        String[] info = s.split("/");
        Double prevscore = userProfileScores.get(info[0] + "/" + info[1] + "/");
        if (prevscore == null) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        } else if (userProfilesScore.get(s) > prevscore) {
            userProfileScores.put(info[0] + "/" + info[1] + "/", userProfilesScore.get(s));
            userProfileLevels.put(info[0] + "/" + info[1] + "/", info[2]);
        }
    }

    //put the final profiles together in this simple form: domain/profile/level of expertise and rank them
    Double totalScore = 0.0;
    for (String s : userProfileScores.keySet())
        totalScore += userProfileScores.get(s);

    Map<String, Double> userProfiles = new HashMap<>();
    for (String s : userProfileLevels.keySet())
        userProfiles.put(s + userProfileLevels.get(s), round(userProfileScores.get(s) * 100 / totalScore, 2));

    userProfiles = sortByValue(userProfiles);

    //find page suggestions for every profile
    HashMap<String, ArrayList<String>> pageSuggestions = new HashMap<>();
    for (String profile : userProfiles.keySet()) {
        String path = crawlerOutputPaths.get(profile);
        ArrayList<String> suggestions = getSuggestions(path, numQueriesSuggestion, pagesPerQuerySuggestion,
                history);
        pageSuggestions.put(profile, suggestions);
    }

    //find alternative profiles for every profile and representative queries
    HashMap<String, HashMap<String, ArrayList<String>>> alternativeProfiles = new HashMap<>();
    for (String userProfile : userProfiles.keySet()) {
        String[] userProfileInfo = userProfile.split("/");
        HashMap<String, ArrayList<String>> profileQueries = new HashMap<>();
        for (String profile : wordvectors.keySet()) {
            String[] profileInfo = profile.split("/");
            if (profileInfo[0].equals(userProfileInfo[0]) && profileInfo[1].equals(userProfileInfo[1])
                    && !profileInfo[2].equals(userProfileInfo[2])) {
                String path = crawlerOutputPaths.get(profile);
                ArrayList<String> queries = getQueries(path, numQueriesExample);
                for (int i = 0; i < queries.size(); i++) {
                    String query = queries.get(i);
                    queries.set(i, query.substring(query.lastIndexOf("\\") + 1).replace("-query", "")
                            .replace("+", " "));
                }
                profileQueries.put(profile, queries);
            }
        }
        alternativeProfiles.put(userProfile, profileQueries);
    }

    //prepare JSON response
    JSONObject response = new JSONObject();
    response.put("userID", userID);
    response.put("timestamp", timestamp);
    JSONArray list = new JSONArray();

    for (String profile : userProfiles.keySet()) {
        JSONObject profileInfo = new JSONObject();
        profileInfo.put("profile", profile);
        profileInfo.put("score", userProfiles.get(profile));

        JSONArray temp = new JSONArray();
        ArrayList<String> suggestions = pageSuggestions.get(profile);
        for (String s : suggestions)
            temp.add(s);
        profileInfo.put("suggestions", temp);

        JSONArray alternativesArray = new JSONArray();
        for (String s : alternativeProfiles.get(profile).keySet()) {
            JSONObject alternativeInfo = new JSONObject();
            alternativeInfo.put("alternative", s);
            ArrayList<String> queries = alternativeProfiles.get(profile).get(s);
            JSONArray queriesArray = new JSONArray();
            for (String str : queries) {
                queriesArray.add(str);
            }
            alternativeInfo.put("queries", queriesArray);
            alternativesArray.add(alternativeInfo);
        }

        profileInfo.put("alternatives", alternativesArray);
        list.add(profileInfo);
    }
    response.put("profiles", list);
    System.out.println("JSON response is ready: " + response);

    //delete previous analysis and store results
    DBCollection collection = db.getCollection("history");
    BasicDBObject previous = new BasicDBObject();
    previous.put("userID", userID);
    collection.remove(previous);
    DBObject dbObject = (DBObject) JSON.parse(response.toString());
    collection.insert(dbObject);
    System.out.println("I saved the analysis...");

}

From source file:edu.nyu.vida.data_polygamy.exp.NoiseExp.java

public HashMap<String, Attribute> addNoise(double increase) {
    HashMap<String, Attribute> newAttributes = new HashMap<String, Attribute>();

    for (String att : attributes.keySet()) {
        if (!(dataAttributesHashSet.contains(att)))
            continue;

        Attribute attribute = attributes.get(att);

        double increment = iqr.get(att) / 10000.0;

        for (int month : attribute.data.keySet()) {
            ArrayList<SpatioTemporalVal> arr = attribute.data.get(month);

            for (int j = 0; j < arr.size(); j++) {
                SpatioTemporalVal val = arr.get(j);
                float noiseIncrement = (float) (r.nextGaussian() * increment * increase);
                val.setVal(val.getVal() + noiseIncrement);
                arr.set(j, val);
            }//from  www.j a v a 2s  .com

            attribute.data.put(month, arr);
        }
        newAttributes.put(att, attribute);
    }

    return newAttributes;
}

From source file:com.lgallardo.qbittorrentclient.RSSFeedActivity.java

private void editRssFeed(final int position, final RSSFeed rssFeed) {

    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(this);
    View addTorrentView = li.inflate(R.layout.add_rss, null);

    // URL input/*ww w . jav  a  2  s .c  o  m*/
    final EditText rssFeedUrlInput = (EditText) addTorrentView.findViewById(R.id.rssFeedUrl);
    final EditText rssFeedNameInput = (EditText) addTorrentView.findViewById(R.id.rssFeedName);
    final EditText rssFeedFilterInput = (EditText) addTorrentView.findViewById(R.id.rssFeedFilter);
    final CheckBox rssFeedAutoDownloadInput = (CheckBox) addTorrentView.findViewById(R.id.rssFeedAutodownload);
    final CheckBox rssFeedNotifyNewInput = (CheckBox) addTorrentView.findViewById(R.id.rssFeedNotifyNew);

    // Set dialog's values
    rssFeedUrlInput.setText(rssFeed.getChannelLink());
    rssFeedNameInput.setText(rssFeed.getChannelTitle());
    rssFeedFilterInput.setText(rssFeed.getChannelFilter());

    rssFeedAutoDownloadInput.setChecked(rssFeed.getAutodDownload());
    rssFeedNotifyNewInput.setChecked(rssFeed.getNotifyNew());

    if (rssFeed != null) {

        if (!isFinishing()) {
            // Dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            // Set add_torrent.xml to AlertDialog builder
            builder.setView(addTorrentView);

            // Cancel
            builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User cancelled the dialog
                }
            });

            // Ok
            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // User accepted the dialog
                    //                        Log.d("Debug", "RSS filter: " + rssFeedFilterInput.getText().toString());

                    // Get values from dialog view
                    String title = rssFeedNameInput.getText().toString();
                    String link = rssFeedUrlInput.getText().toString();
                    String filter = rssFeedFilterInput.getText().toString();

                    boolean autoDownload = rssFeedAutoDownloadInput.isChecked() ? true : false;
                    boolean notifyNew = rssFeedNotifyNewInput.isChecked() ? true : false;

                    //Save RSS feed

                    if (link != null && !link.isEmpty()) {

                        if (title == null || title.isEmpty()) {
                            title = link;
                        }

                        rssFeed.setChannelTitle(title);
                        rssFeed.setChannelLink(link);
                        rssFeed.setChannelFilter(filter);
                        rssFeed.setAutodDownload(autoDownload);
                        rssFeed.setNotifyNew(notifyNew);
                        //
                        //
                        //                            // Refresh channel list
                        //                            mSwipeRefreshLayout.setRefreshing(true);
                        //                            new rssFeedsTask().execute();

                        ArrayList<RSSFeed> rssChannels = myadapter.getRssChannels();

                        rssChannels.set(position, rssFeed);

                        myadapter.setRssChannels(rssChannels);
                        myadapter.notifyDataSetChanged();

                        // Save all;
                        rss_feeds = "";
                        for (int i = 0; i < rssChannels.size(); i++) {
                            RSSFeed rssFeed = rssChannels.get(i);

                            //                                Log.d("Debug", "Saving: " + rssFeed.getChannelTitle() + ";" +  rssFeed.getChannelLink() + ";" +  rssFeed.getChannelPubDate() + ";" +  rssFeed.getAutodDownload() + ";" + rssFeed.getNotifyNew());

                            saveRssFeed(rssFeed.getChannelTitle(), rssFeed.getChannelLink(),
                                    rssFeed.getChannelFilter(), rssFeed.getChannelPubDate(),
                                    rssFeed.getAutodDownload(), rssFeed.getNotifyNew());
                        }

                    }

                }
            });

            // Create dialog
            AlertDialog dialog = builder.create();

            // Show dialog
            dialog.show();
        }
    }

}