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 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;
}
Related
I'm updating my Android app. The app retrieves data from my server and among that data is a user id. The user id is a number (Integer) but it arrives from the server as a string eg "1234". In the old version I then saved this user id as a string in my shared prefernces but now that I'm looking back at it I don't like this and want to save it as an Integer as it should be.
So far pretty simple. I just use putInt / getInt rather than putString / getString. The problem is that all the people currently using the app will have the value saved in their shared preferences as a string and then when they update the app the new version of the app will start to try to use getInt to get the value which the old version saved as a string.
What's the best way to avoid any errors because of this and ensure a smoothe transition between the two app versions?
Thanks.
Something like that in your onCreate:
try{
prefs.getInt("key", 0);
}catch (ClassCastException e){
Integer uid = Integer.parseInt(prefs.getString("key", null);
if(uid != null)
prefs.edit().putInt("key", uid).commit();
}
This is as simple as
int userid = Integer.parseInt( preferences.getString("userid", ""));
First of all convert you string user id into integer like,
int uid=Integer.parseInt("1234");//here is your string user id in place of 1234.
and then write uid into your shared preference with putExtra(key,intValue).
that's it.
Please excuse me if I am being a noob, but I just completed an Android programming tutorial, and tried making my own app, but don't know how to do something (which is ok, right?). So yeah, I made a simple calculator app, and tried to have it notify the user the result, so I made an int called result which is the value of two editTexts added together. I tried making a notification with the contentText being the result int, but I don't reallyknow how to do that as it will only take a string... Help. If you need the code the just say so.
You can convert the int to a String using Strings valueOf method:
String string = String.valueOf(result);
Or you could use String format method if you wish to have text too:
int result = 0;
String.format("Result: %d", result);
Try converting int to String like this
String resultString = String.valueOf(resultInt);
I've made an offline currency convertor that gets the users input in the EditText section using a TextWatcher and returns the required ouptut from methods...and I"ve made it an a way that the user cannot insert a "null" value in the EditText section and then press the convert button by using euro.getText !==null for example.But I don't know how to proceed when the user leaves some space between the input,for instance 29 50.This will make my program to crash.My question what should I use to check for an input with space in order to avoid a program crash?Thank you.
Your program crashes with number format exception. You can do so:
try{
double value = Double.parseDouble(editText.getText().toString());
} catch(NumberFormatException ex){
Log.e(TAG, "improper number format");
//show some dialog saying what's the format that should be entered
}
You can also go with a regex:
String editTextValue = editText.getText().toString();
if(editTextValue.matches("\\d+\\.\\d+")){
double value = Double.parseDouble(editTextValue);
} else{
//show dialog saying what should be the format.
}
This is actually quite easy.
Does your app accept numbers with a comma or a dot? Either way, you can simply replace the String by the symbol of you choice by using the following:
String unspaced = edittext.getText().toString().replace(' ', '.'); // or , depending on what your app uses
I am trying to pass a text from the spinner. Actually the spinner contains the textx which I have fetched from the server side of my application.
So what I am trying to do is that, as soon as I select text from the spinner, I want that string to be passed to the server side. So here i am passing the text to a function which can make a request to the JSP.
Main part of the code(android)
categ = ((TextView) selectedItemView).getText().toString();
postData(categ);
//Remaining section
public void postData(categ)
{
String page="processing_pages/individual_phone_communicator.jsp?rom="+categ;
result = ws.getWebData(page);
if (result != null)
plotData();
else
alerter("null");
}
(It is returning a null value always.But when i am directly running the same query without any parameter and taking the value directly at the JSP page, it shows result)
Now it will move to the JSP.
String hk=request.getParameter("rom");
Now i am running a query like this:
sqlstatem="select first_name,latitude,longitude from tbluserdetails where user_id=(select user_id from tblindividual_job where jcat_id=(select jcat_id from tbljobcat where job_name='"+hk+"'))";
I am expecting it to give back data in the form of json array. But instead it is showing an error. I tried entering the parameter directly from browser even. Sometimes, the page is displaying correct answer with above query. This makes me more confusing. But when i tried with numbers such as 1 or 2 from the eclipse:
String page="processing_pages/individual_phone_communicator.jsp?rom=2"
and modified the query by trying the exact word instead of 'hk' like this
int rom=Integer.parseInt(request.getParameter("romo"));
if(rom==1)
{
sqlstatem="select first_name,latitude,longitude from tbluserdetails";
}
else
{
sqlstatem="select first_name,latitude,longitude from tbluserdetails where user_id=(select user_id from tblindividual_job where jcat_id=(select jcat_id from tbljobcat where job_name='Blood donar'))";
}
it is running correctly. From browser also, it is running correctly when i pass integer as parameter. But i need it to be running by taking a text from the emulator as parameter.
But when I try, like this:
String page="processing_pages/individual_phone_communicator.jsp?rom=Blood donor"
Then also i am getting null as result. What I assume is that, my JSP page is only taking integer parameters, I don't know why it is happening.
I am using net beans for JSP. Kindly find me a solution for this issue. Kindly ignore if the question is childish, as i am just a beginner.
I don't know what the "ws" variable is, but the IP for your local machine (not the phone) in the android emulator is 10.0.2.2. So any URL pointing to a local web app on your machine should start with http://10.0.2.2/...
Mike
Why does this code trigger a force close in Android?
`score.setText(Integer.parseInt((String) score.getText())+1);`
score is a TextView, and I am simply increasing the number by 1. I have predefined a String resource to be the initial number in the score TextView.
I am quite frustrated.
First off you should try breaking down your code so you can actually see what is going on with it.
Instead of
score.setText(Integer.parseInt((String) score.getText())+1);
try
String tmp = score.getText().toString();
int score;
score = Integer.parseInt(tmp) + 1;
score.setText(String.valueOf(score));
EDIT: Upon further reading of the documentation, setText has several overloads, one of which DOES take an int, but it takes the int of a resource ID. My guess is that your score is not a valid resource ID, thus crashing your application.
public final void setText (int resid)
Oh and as far as the frequent FC's when beginning Android Dev, it happens to the best of us. The key is to learn WHY the FC's happen, and have a LOT of patience.
mostly u need to do this
score.setText(Integer.parseInt(score.getText().toString())+1);
coz.. getText() returns a Editable Object which cannot be parsed to Integer. So it give NumberFormat Exception.
AndMake sure to set TextView,s Text to an integer initially..
try this way
score.setText(String.valueOf(Integer.parseInt(score.getText().toString())+1));
as you can pass the integer value that's why getting force the application
TextEdit.setText takes a CharSequence as input.
You are supplying an integer through Integer.parseInt((String) score.getText())+1
See, if converting it back to string and using it in setText helps.
You can convert an integer to string using Integer.toString.
PS: I am new to java myself.
The compiler should have ideally caught this error.
It's possible java uses some implicit type conversions from string to int.