EditBoxPreference() storing the value as an int instead a string
I'm writing an Android application that can easily back up files and folders to the users PC. One of the things I wanted to implement was allowing the client running on the Android device to change the port I will be sending the file to.
For this, I've created an EditTextPreference to store the value.
The code I'm using to get this value back is
port = prefs.getString("serverPort", "<unset>");
However, this returns a string and I need an int, so I tried to use
sendPort = Integer.parseInt(port);
But this crashes the Android application, with (I think) a number format exception.
Is there anyway I can explicitly store the value that is entered as an Integer to make it easier?
I tried to use the method
port = prefs.getInt(...);
but that didn't work either.
Thanks 开发者_C百科for any help.
This will take whatever is entered into your edit text and put it in an int.
int yourValue = Integer.valueOf(editText.getText().toString());
Note that Integer.valueOf() will return a format exception if you put a String in it that doesn't have an integer value.
You can then use
prefsEdit.putInt("serverPort", yourValue);
prefsEdit.commit();
to save it to preferences. And this to retrieve it
int port = prefs.getInt("serverPort", -1);
Saving the port as String
or int
doesn't make a big difference. Either way you'll have to convert it.
Your app crashes, because it cannot convert <unset>
to a number, that's where the NumberFormatException
comes from.
Solution:
Catch the NumberFormatException
and set sendPort
to a default value.
port = prefs.getString("serverPort", "<unset>");
try {
sendPort = Integer.parseInt(port);
} catch (NumberFormatException ex) {
sendPort = 1234;
}
精彩评论