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.
}
Related
I got an EditText and I want to insert an int type variable into my database. If I insert a number, everything's ok. But if I left the EditText empty, the app crashes. This is the code that handles this and I think it's an Integer.toString() problem or something like this.
int target;
if (targetNumber.getText().toString().isEmpty()) {
target = Integer.parseInt("");
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
You can't parse "" to int. You can store 0 for example
int target;
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
Replace this
target = Integer.parseInt("");
with
target = 0;
If you'd like to make use of a ternary operator:
int target = targetNumber.getText().toString().isEmpty() ? 0 : Integer.parseInt(targetNumber.getText().toString())
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));
Im in the process of learning some app building for android.
I wanna create an example of a high score system before trying to use it in a game.
Lets say that I have a timer running seconds and a stop button. If I press the stop button, the timer stops, and the number it has come to is saved (locally) to a highscore list. A top 5 for example.
How would I go about saving this highscore?
I've read a bit about SQLite and Shared preference, but I don't know what to use. Maybe there are even more options? I'm not looking for any online highscore list.
If you know of some good guides / tutorials, please link them to me.
Thanks.
I use SharedPreferences for that kind of thing although it is a bit overly complex in my opinion. Once you've got it added to your manifest and figure out how to use it, however, it's fairly simply. It looks like the usage of SharedPreferences has been covered previously here: How to use SharedPreferences in Android to store, fetch and edit values. You can, of course, just save to a file as well which might be easier, but potentially easier to hack if you care. I don't know much about SQLight to make comments on that.
Yes shared preferences would be suited for this. Here is a kick off example - but better use lists :
private static final String[] SCORES_KEYS = { "1", "2", "3", "4", "5" };
private static final int SCORES = 5;
//...
{
SharedPreferences sp = getDefaultSharedPreferences(); // in an activity,
// service or other context. DO NOT USE NAMED preferences
final long timer = getYourTimerScore();
int position = SCORES;
long[] lowerScores = new long[SCORES + 1];
for (int i = SCORES; i > 0;) {
long j = sp.getLong(SCORES_KEYS[--i], 0);
if (j < timer) {
--position;
lowerScores[i + 1] = j;
} else break;
}
if (position < SCORES) {
lowerScores[position] = timer;
Editor ed = sp.edit();
for (int i = position; i < SCORES; ++i) {
ed.putLong(SCORES_KEYS[i], lowerScores[i]);
}
ed.commit();
}
}
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 am trying to compare items out of my DB to the value of an EditText (user input). The answer can have multiple answers, seperated by a ','. I first put them into a stringarray and then compare them to the answer. The LevenshteinDistance checks if the answer is more or les good (http://en.wikipedia.org/wiki/Levenshtein_distance#Computing_Levenshtein_distance).
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
for (String answer : answers) {
if (answer.equals(userAnswer)) {
Toast.makeText(getApplicationContext(), ("Answer Correct"),
Toast.LENGTH_SHORT).show();
tvMessage.setText("You smartass!");
} else {
Toast.makeText(getApplicationContext(), ("Wrong"),
Toast.LENGTH_SHORT).show();
points = points - 4;
String answerGood = answer.toLowerCase();
LevenshteinDistance lDistance = new LevenshteinDistance();
int comparisonCheck = lDistance.computeLevenshteinDistance(
userAnswer, answerGood);
if (comparisonCheck == 1) {
tvMessage.setText("Almost there, but not quite yet!");
} else if (comparisonCheck > 1) {
tvMessage.setText("Are you serious, totally wrong?!");
}
}
}
Suppose I am having the answers for a question in the DB as follows: tree,test,radio
I am having two problems:
1. When I type "radi" it gives me 'Almost there...' which is good. It should also give me this if I enter "tes", but instead it gives me the 'Are you serious,...' line. I guess it keeps comparing to the last one.
2. Every time I type in something which is not correct, I get -12 instead of -4. I suppose this is due to the fact I am having three answers and it loops three times.. but I don't know how I can make it count only once..
Anyone can help me on the way? Thanks!
Assuming you don't need to know the word which gives the least Levenshtein distance, you could modify your loop to find smallest distance only;
userAnswer = etUserAnswer.getText().toString().toLowerCase();
String[] answers = qAnswer.split(",");
LevenshteinDistance lDistance = new LevenshteinDistance();
int minDistance = lDistance.computeLevenshteinDistance(
userAnswer, answers[0].toLowerCase());
for (int i = 1; i < answers.length; ++i) {
minDistance = Math.min(minDistance, lDistance.computeLevenshteinDistance(
userAnswer, answers[i].toLowerCase()));
}
if (minDistance == 0) {
// Correct answer...
} else {
// Wrong answer...
points -= 4;
// etc etc...
}