Chief Delphi

Chief Delphi (http://www.chiefdelphi.com/forums/index.php)
-   Java (http://www.chiefdelphi.com/forums/forumdisplay.php?f=184)
-   -   Preferences check if the element exists (http://www.chiefdelphi.com/forums/showthread.php?t=106805)

joelg236 05-06-2012 16:50

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.

Code:

/**
    * 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. :)

joelg236 05-07-2012 22:18

Re: Preferences check if the element exists
 
I found the solution to this problem, so I'll post the answer for reference.

Code:

    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.


All times are GMT -5. The time now is 09:14.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.
Copyright © Chief Delphi