I am new to using shared preferences and on my first try im getting errors that don't make sense to me. I assign a value like this:
int saveScore = sp.getInt("SAVE_SPOT",0); //This is intentional to get the
//default value of 0 to go to case 0
switch(saveScore){
case 0:
SharedPreferences.Editor edit1 = sp.edit();
edit1.putInt("SCORE_1", score);
edit1.putInt("SAVE_SPOT", 1);
edit1.commit();
break;
case 1:
int previous_score = sp.getInt("SCORE_1",0); // error happens here
if(sp.getInt("SCORE_1",0)>score){
SharedPreferences.Editor edit2 = sp.edit();
edit2.putInt("SCORE_2", score);
edit2.putInt("SAVE_SPOT", 2);
edit2.commit();
}
else{
SharedPreferences.Editor edit3 = sp.edit();
edit3.putInt("SCORE_2", previous_score);
edit3.putInt("SCORE_1", score);
edit3.putInt("SAVE_SPOT", 1);
edit3.commit();
}
break;
Every time i run the program i get the error "string cannot be cast to integer". I am almost 99% sure the variable score is an int and not a string but I am not sure why i am getting this error.
You can check to make 100% it is an int by using this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
If putInt won't work, you could use Integer.parseInt( instead.
I solved my issue, un installing the app is necessary every time in testing because thats the only way to clear the stored data
It seems that with putInt() it won't let you put anything but an int, so that is odd. Are you really telling the full story here?
My guess is that you have ANOTHER key that has the name SCORE_1 that was actually stored as a string, and when you're grabbing out the int, it's picking up the String instead. That's the only way. According to the API:
Throws ClassCastException if there is a preference with this name that is not an int.
So I think SCORE_1 is already in there, and was stored as a string. For the hell of it, try to get out SCORE_1 using getString() instead.
See here: http://developer.android.com/reference/android/content/SharedPreferences.html#getInt%28java.lang.String,%20int%29
Related
So first of all sorry if this has already been asked and answered before, I couldn't find anything relating to my issue.
So I'm working on a project for college and I need to get int values from EditText widgets. I was told to use parseInt to do this however when running my program, that line of code causes the application to crash. I don't know what I'm doing wrong, I'm still very new to android development, thanks for the help :)
public void Calculate (View view)
{
int MilesTravelled;
int FuelUsed;
int MPG;
/* the two lines below are what cause the application to crash */
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
FuelUsed = (int) (FuelUsed / 4.55);
MPG = MilesTravelled / FuelUsed;
lblMPG.setText(FuelUsed);
}
Do you have this in the onCreate() function?
EditText txtMilesTravelled = (EditText) findViewById(R.id.YourEditText);
But I think you mixed Integer and int. They are not the same:
See this link!
First of all, don't capitalize the first letter of an variables or method names. Following the Java coding conventions, only do that for classes.
What is probably causing your app to crash is you trying to set the text of a label to an integer. The setText method for a TextView needs to take in a string.
So change:
lblMPG.setText(FuelUsed);
to:
lblMPG.setText(String.valueOf(FuelUsed));
Otherwise it might be that it's trying to parse a non-numerical string to an integer.
For exmaple, if the EditText is blank, it will cause your app to crash. To prevent that, try this:
int MilesTravelled = 0, FuelUsed = 0;
try {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} catch (NumberFormatException nfe) {
Toast.makeText(getApplicationContext(), "Error NFE!", 0).show();
nfe.printStackTrace();
}
This way, it will catch a NumberFormatException error (parsing a string to an integer that can't be represented as an integer, such as "hello"). If it catches the error, it will toast that an error has occurred and your integer variables will remain 0.
Or you could just test if the strings contain only digits using the following regex:
int MilesTravelled = 0, FuelUsed = 0;
if (txtMilesTravelled.getText().toString().matches("[0-9]+")) {
MilesTravelled = Integer.parseInt(txtMilesTravelled.getText().toString());
} else {
// contains characters that are not digits
}
if (txtFuelUsed.getText().toString().matches("[0-9]+")) {
FuelUsed = Integer.parseInt(txtFuelUsed.getText().toString());
} else {
// contains characters that are not digits
}
If that's not the problem, then make sure you define your variables properly.
txtMilesTravelled and txtFuelUsed should be EditText:
EditText txtMilesTravelled = (EditText)findViewById(R.id.txtMilesTravelled);
EditText txtFuelUsed = (EditText)findViewById(R.id.txtFuelUsed);
And make sure that your R.id.editText actually exists on your layout and that the IDs are the correct ones.
Last thing, make sure FuelUsed is not 0 before calculating MPG because then you are dividing by 0:
int MPG = 0;
if (FuelUsed != 0) {
MPG = MilesTravelled / FuelUsed;
}
I am assuming that you're entering perfect integers in the EditTexts. It might be a good idea to use the trim function txtMilesTravelled.getText().toString().trim() before using parseInt.
However, I think the major problem is here : lblMPG.setText(FuelUsed);
FuelUsed is an integral value, when you pass an integer to setText(), it looks for a string resource with that integral value. So you should be passing a String to the setText() method.
Use : lblMPG.setText(Integer.toString(FuelUsed));
I am working with numbers, I get an int from shared preferences, I do some maths and then
I want to do something IF the result is situated between 2 numbers.
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", Context.MODE_PRIVATE);
int A = settings.getInt("A", 1);
int B = settings.getInt("B", 1);
operation = (TextView) findViewById(R.id.imc );
operation.setText(A*B);
String operation;
if (SOMETHING HERE!) { // is situated between 1 and 20
something
}
What should I do?
Any suggestin will be apreciated.
You just need a simple logic dude.Do the following,
if(A>1 && A<20)
{
//Do what ever you want.
}
I have this code :
String[] whereyoufromarray = {"where", "you", "from"};
for (String whereyoufromstring : whereyoufromarray)
{
if (value.contains(whereyoufromstring)) {
//statement
}
}
But I want that if to only execute the statement if "value" has all of the words included in the array, something like "where are you from?". Currently if value has ONLY one of the words in the array the statement is executed.
I can do this with if (value.contains("where") && value.contains("you") && value.contains ("from")) but this just seems unnecessarily long. There has to be a workaround using arrays that I am missing.
Well, what is it?
p.s.: sorry for poor grammar. i'm suffering from sleep deprivation.
String[] whereyoufromarray = {"where", "you", "from"};
boolean valueContainsAllWordsInArray = true;
for (String whereyoufromstring : whereyoufromarray) {
// If one word wasn't found, the search is over, break the loop
if(!valueContainsAllWordsInArray) break;
valueContainsAllWordsInArray = valueContainsAllWordsInArray &&
value.contains(whereyoufromstring);
}
// valueContainsAllWordsInArray is now assigned to true only if value contains
// ALL strings in the array
For a case like this, I typically implement a function just to make the test. Let's call it containsAll()
public static boolean containsAll(String[] strings, String test)
{
for (String str : strings)
if (!test.contains(str))
return false;
return true;
}
And now you just do
if (containsAll(whereyoufromarray, value))
//statement
String[] whereyoufromarray = {"where", "you", "from"};
int arrayLength = whereyoufromarray.length;
int itemCount = 0;
for(String whereyoufromstring : whereyoufromarray)
{
if(value.contains(whereyoufromstring))
{
itemCount++;
}
}
if (itemCount == arrayLength){
//do your thing here
}
rough idea. I don't have my IDE up to proof this, but basically you can set a counter to = the length of your known array, then check each value in the array to see if it contains a match..if it does, increment another counter. At the end, test your counter to see if it matches the length of your array, so in your example, if itemCount= 3, then all values matched. if it was 2, then one would be missing and your method wouldn't execute.
I have the weirdest problem...
all I am trying to do is to get the value from a EditText and do some validation.
The value in the edittext must be between 1 and 10. However, even if I enter any number between 1 or 10 , it still validates false. I even tested the edittext input to make sure it is correct , and it is, but the if still fails . Any ideas ?
here is the code:
ed = (EditText) dialog2.findViewById(R.id.ed_quantity);
Button bq = (Button) dialog2.findViewById(R.id.alert_a);
dialog2.setCancelable(false);
dialog2.show();
bq.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
String test = ed.getText().toString();
Toast toast23452234 = Toast.makeText(mContext, "Quantity: "+test, Toast.LENGTH_LONG);
toast23452234.show();
if(test=="1"||test=="2"||test=="3"||test=="4"||test=="5"||test=="6"||test=="7"||test=="8"||test=="9"||test=="10")
{
quantity = Integer.parseInt(ed.getText().toString());
dialog2.dismiss();
ed.setText("1");
}
else
{
Toast toast2345223 = Toast.makeText(mContext, "Quantity must be between 1 and 10" , Toast.LENGTH_LONG);
toast2345223.show();
}
}
});
try this
test.trim().equalsIgnoreCase("1")
in your if-condition
Use equals method to compare strings..
if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))
or use int to compare
int test = Integer.valueOf(ed.getText().toString());
String is not a native type so you can't do test=="1". This compares the object references and obviously the two objects have different references.
Call equals(Object object) method on string object. Like,
test.isEquals("1")
Better parse the input string to integer as
int testInteger = Integer.parseInt(test);
and compare as
if(testInteger==1 || testInteger ==2)
This saves many method calls to string object.
use .equals("") in case of String.
if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))
use .equals on string operation instead of ==
if(test.equals("1")||... and so on)
or else convert string into "int".
Use test.equals("1") || .....
You can also do this
int t = Integer.parseInt(test);
if(t == 1 || t == 2 || ...)
I am trying to get integer value entered in EditText by user.
EditText eTextValue=(EditText) findViewById(R.id.eId);
String eTextString=eTextValue.getText().toString();
int eTextValue1=Integer.parseInt(eTextString);
But unluckily I am getting,
unable to parse 9827328 as integer.
I have tried using Integer.valueOf instead of Integer.parseInt but again I am getting the same exception.
I have even used Long datatype to store value instead of int type datatype but nothing seems to be working.Any help over this will be highly appreciated.
I have gone through all these links unable to parse ' ' as integer in android , Parsing value from EditText...but nothing seems to be working all of them are landing me in exception.
You are using eTextValue as a variable name for two different things (an int and an EditText). You cant do that and expect it to work properly. Change one or the other and it should work better.
Try by entering the following in the XML File under the corresponding EditText element.
android:inputType="number"
Hope this should get you pass the exception.
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(eTextString)
int eTextValue1=Integer.parseInt(eTextString);
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps
int id;
id=Integer.parseInt(ed.getText().toString());