Preferences check if the element exists

Hi CD,

I am working on some code to interface with the preferences class that is accessible in SmartDashboard. Unfortunately, I don’t know how to figure this part out.

/**
     * Gets the integer from preferences.
     * 
     * @param ID ID of the integer
     * @param backupValue The value to return in preferences does not contain it
     * @param replace If the backup value has to be used, should the value be inserted?
     * @return Returns the integer saved in preferences
     */
    public static int getInt(String ID, int backupValue, boolean replace) {
        int backup = backupValue;
        try {
            if(m_data.elementAt(m_names.indexOf(ID)) != null) {
                backup = ((Integer)m_data.elementAt(m_names.indexOf(ID))).intValue();
// Checks to see if my code has the element stored^^^ 
            }
        }
        catch(ClassCastException ex) {} 
        catch(ArrayIndexOutOfBoundsException ex) {}
//These exceptions are okay to catch because my code might not store it already
        if (Preferences.getInstance().getInt(ID, backup) == backup && replace) { 
// This is where I have a problem. I can check if its the same as backup - 
//which will happen when it goes to the backup value yes, which does its 
//purpose. But for optimization, everytime the field is actually the backup 
//(No matter if it exists or not), it will save the value. That takes up 
//bandwidth and slows the code down. NOT what I want to do, especially 
//because a lot of the values will be the same as backup.
            Preferences.getInstance().putInt(ID, backup);
            save();
        }
        return Preferences.getInstance().getInt(ID, backup);
    }

I wrote the problem in the code in comments, just in case you didn’t notice it. :slight_smile:

I found the solution to this problem, so I’ll post the answer for reference.


    public static String getSetting(String name) throws NoSettingFound {
        if(Preferences.getInstance().containsKey(name)) {
            return Preferences.getInstance().getString(name, null);
        }else {
            throw new Errs.NoSettingFound(name);
        }
    }

Basically, there is a method meant just for this problem.