Displaying Content w/ Button Clicks - java

I have ten buttons, 0-9 and when one is pressed I want to display its value into a TextView. So the initial display looks like this:
0.00
If I press the 2 button then it should be displayed to the TextView like this:
0.02
Now if I pressed 5 then the new value should be:
0.25
and so on. I've never done anything like this so I'm not exactly sure where to begin. So my question is, whats the best way to implement something like this?
EDIT: I know how to display content when a button is pressed, however, I'm not sure how to transition the each number when a new button is pressed into its new position.

Store an int with the value you are displaying and as you input the number multiply that value by 10 and add the new number on.
Something like:
public void updateValue(int buttonPressed){
currentValue = (currentValue*10) + buttonPressed;
}
then where you're updating the TextView make sure you format the string in a suitable way:
public String formatNum(){
String valueAsString = Integer.toString(currentValue);
while(valueAsString.length()<3){
valueAsString = '0' + valueAsString;
}
char[] stringBuilding = new char[valueAsString.length()+(((valueAsString.length())-2)/3)+1];
int valueAsStringPtr = valueAsString.length()-1;
int stringBuildingPtr = stringBuilding.length-1;
while(stringBuildingPtr>=0){
if(stringBuildingPtr==stringBuilding.length-3){
stringBuilding[stringBuildingPtr--] = '.';
} else if((stringBuilding.length-stringBuildingPtr-3)%4==0){
stringBuilding[stringBuildingPtr--] = ',';
} else {
stringBuilding[stringBuildingPtr--] = valueAsString.charAt(valueAsStringPtr--);
}
}
String returnVal = String.copyValueOf(stringBuilding);
return returnVal;
}
All this assumes you have an integer field currentValue.
Also try to do this on a worker thread ideally to avoid lagging out UI, it shouldn't really take too long, but still a good idea.
Note: for anyone wondering why I elected to use ints instead of float/double is because then we will introduce error displaying a binary representation as a decimal.

Related

Android EditText setEnabled(false) isn't working

I have a couple of dynamically created EditText fields.
I am trying to disable the fields if the value in another field doesn't match certain criteria.
The issue is that if other criteria is met, the field is disabled properly by setting setEnabled(false);.
Essentially in a part number field, we check if the part number requires a serial number or a lot number.
If the part requires a serial number, the serial number field displays an error, the lot number field is disabled, and the quantity field is set to "1" and disabled
If a lot number is required, the lot number field shows an error and the serial number field is disabled. This works as intended.
public void onTextChanged(#NotNull EditText target, #NotNull Editable s) {
int serialIndex = 4;
int lotIndex = 5;
int quantityIndex = 6;
EditText serial = findViewById(serialIndex);
EditText lot = findViewById(lotIndex);
EditText quantity = findViewById(quantityIndex);
String txt = partNum.getText().toString().toUpperCase();
partNumber = txt;
Global.isSerialized = DatabaseManager.isSerialized(txt);
Global.isLot = DatabaseManager.isLot(txt);
//this is not working. The fields do not get disabled.
if (!Global.isSerialized && !Global.isLot) {
lot.setEnabled(false);
serial.setEnabled(false);
findViewById(id).setNextFocusDownId(quantityIndex);
}
if (txt.equals("")) {
serial.setError(null);
lot.setError(null);
if (!quantity.isEnabled()) {
quantity.setEnabled(true);
quantity.setText("");
}
}
//This is working. The lot number field gets disabled.
if (Global.isSerialized) {
lot.setEnabled(false);
snRequired = true;
serial.setError("Serial Number Required");
quantity.setText("1");
quantity.setEnabled(false);
findViewById(id).setNextFocusDownId(serialIndex);
} else {
snRequired = false;
serial.setError(null);
quantity.setText("");
quantity.setEnabled(true);
}
//this is also working. The serial number field gets disabled.
if (Global.isLot) {
lot.setEnabled(true);
lnRequired = true;
lot.setError("Lot Number Required");
serial.setEnabled(false);
quantity.setText("");
quantity.setEnabled(true);
findViewById(id).setNextFocusDownId(lotIndex);
} else {
lot.setError(null);
lnRequired = false;
}
Any ideas?
I'm surprised this is still an issue. It's been asked before way back in the past: How to set editable true/false EditText in Android programmatically?
Maybe try this and see what comes of it?
I was able to figure it out. Hard coding the field indexes was the wrong approach. I was able to get the proper indexes by using a for loop on a fieldList array, and assigning the indexes to the variables based on the name of the field. Once I did that, I was able to setEnabled(true) or setEnabled(false) as needed without issue.

Making JRadioButton random

my data comes from query like this to my radio buttons:
radio1.setText(Question.get(i).getChoiceOne()) // assign ist choice to ist radio button
radio2.setText(Question.get(i).getChoiceTwo()) // assign second choice to second radio
radio3.setText(Question.get(i).getcorrectchoice()) // assign correct choice to third radio button
In this case each time the correct answer is assigned to third radio button which makes the quiz predictable.. Can I do it in some way where the correct choice some times assign to first radio, some times to second and so on?
You could do following:
String one = Question.get(i).getChoiceOne();
String two = Question.get(i).getChoiceTwo();
String three = Question.get(i).getcorrectchoice();
// construct list from questions.
List<String> choices = Arrays.asList(one, two, three);
// give random order to list
Collections.shuffle(choices);
// set radio button texts
radio1.setText(choices.get(0));
radio2.setText(choices.get(1));
radio3.setText(choices.get(2));
int i = (Math.random() * 1000)%3;// generate a values between 0-2
String[] answers = new String[3];
answers[i] = Question.get(i).getcorrectchoice();// i is the index of right answer
// insert the 2 other answers, what ever i you chose (i+1)%3 will put them in the remaining 2 places
answer[(i+1)%3] = Question.get(i).getfirstchoice();
answer[(i+1)%3] = Question.get(i).getsecondchoice();
i = (i+1)%3;// the original value of i
// insert radios
radio1.setText(answers[0]);
radio2.setText(answers[1]);
radio3.setText(answers[2]);
// get the right answer; get the text of the selected radio
if(textOfselectedRadio.quals(answers[i])){
// correct
}

for loop jumps to last number in java android development

Hi I am making an android App, I want to add some values to a database and I want to do N times so I used a for loop as seen below:
private void addCodeToDataBase() {
for (int i = 1; i <= 100; i++) {
//indexnumber is a TextView
indexNumber.setText("Please enter the TAN code for Index number " + i);
//tanCode is an EditText
if (tanCode.getText().toString() != null) {
//index here is just an int so i can use the i inside the onClick
index = i;
//add is a button
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String codeText = tanCode.getText().toString();
dbHandler.addcode(index, codeText);
}
});
} else {
Toast.makeText(addcode.this, "Please enter your code !!!", Toast.LENGTH_LONG).show();
}
}
}
but what I am facing here is the for loop jumps to 100 at the first run, What I mean is the text will show :
Please enter the TAN code for Index number 100
it skips 99 numbers!! how would I fix it ?
It's Because your for loop executes so fast that you can't notice that the change of the text.First i is 0,and then it becomes 1,then the text will be "Please enter the TAN code for Index number 1" ......
your loop is working correctly but it is replacing text on each iteration that's why you think that it is jumping on last value please use break point and debug you will see each value on each iteration or use log in which you will see each value
It's not easy to imagine what your code does without seeing your declarations of indexNumber, tanCode, index, and, in particular, add. So, e.g., we don't know how often your if condition yields true.
However, most probably, the problem is that your assignment add.setOnClickListener(...) is just iterated with no user interaction in between. Now if you repeatedly assign something to your add (whatever that is), the last assignment will win.
If you want 100 buttons, you'll need to have an array or List of buttons to press, where each has a different tan code. If you want one button that repeatedly asks for the different tans, then you have to assign the data for click i + 1 only after click i has been handled, i.e. in the on click listener.
To give more specific help, we would need to know how your user interface should look (how many widgets of what kind) and how each widget should behave.

Calculate Dice Roll from Text Field

QUESTION:
How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll?
CLARIFIER:
I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a dice roll. Then, add up all the rolls and numbers to get a total. Much like how Roll20 does with their /roll command for an example. If !clarifying {lstThen.add("look at the Roll20 and play with the /roll command to understand it")} else if !understandStill {lstThen.add("I do not know what to say, someone else could try explaining it better...")}
Info:
I was making a Java program for Dungeons and Dragons, only to find that I have come across a problem in figuring out how to calculate the user input: I do not know how to evaluate a string such as this.
I theorize that I may need Java's eval at the end. I do know what I want to happen/have a theory on how to execute (this is more so PseudoCode than Java):
Random rand = new Random();
int i = 0;
String toEval;
String char;
String roll = txtField.getText();
while (i<roll.length) {
check if character at i position is a d, then highlight the numbers
after d until it comes to a special character/!aNumber
// so if d was found before 100, it will then highlight 100 and stop
// if the character is a symbol or the end of the string
if d appears {
char = rand.nextInt(#);
i + #'s of places;
// so when i++ occurs, it will move past whatever d# was in case
// d# was something like d100, d12, or d5291
} else {
char = roll.length[i];
}
toEval = toEval + char;
i++;
}
perform evaluation method on toEval to get a resulting number
list.add(roll + " = " + evaluated toEval);
EDIT:
With weston's help, I have honed in on what is likely needed, using a splitter with an array, it can detect certain symbols and add it into a list. However, it is my fault for not clarifying on what else was needed. The pseudocode above doesn't helpfully so this is what else I need to figure out.
roll.split("(+-/*^)");
As this part is what is also tripping me up. Should I make splits where there are numbers too? So an equation like:
String[] numbers = roll.split("(+-/*^)");
String[] symbols = roll.split("1234567890d")
// Rough idea for long way
loop statement {
loop to check for parentheses {
set operation to be done first
}
if symbol {
loop for symbol check {
perform operations
}}} // ending this since it looks like a bad way to do it...
// Better idea, originally thought up today (5/11/15)
int val[];
int re = 1;
loop {
if (list[i].containsIgnoreCase(d)) {
val[]=list[i].splitIgnoreCase("d");
list[i] = 0;
while (re <= val[0]) {
list[i] = list[i] + (rand.nextInt(val[1]) + 1);
re++;
}
}
}
// then create a string out of list[]/numbers[] and put together with
// symbols[] and use Java's evaluator for the String
wenton had it, it just seemed like it wasn't doing it for me (until I realised I wasn't specific on what I wanted) so basically to update, the string I want evaluated is (I know it's a little unorthodox, but it's to make a point; I also hope this clarifies even further of what is needed to make it work):
(3d12^d2-2)+d4(2*d4/d2)
From reading this, you may see the spots that I do not know how to perform very well... But that is why I am asking all you lovely, smart programmers out there! I hope I asked this clearly enough and thank you for your time :3
The trick with any programming problem is to break it up and write a method for each part, so below I have a method for rolling one dice, which is called by the one for rolling many.
private Random rand = new Random();
/**
* #param roll can be a multipart roll which is run and added up. e.g. d6+2-d4
*/
public int multiPartRoll(String roll) {
String[] parts = roll.split("(?=[+-])"); //split by +-, keeping them
int total = 0;
for (String partOfRoll : parts) { //roll each dice specified
total += singleRoll(partOfRoll);
}
return total;
}
/**
* #param roll can be fixed value, examples -1, +2, 15 or a dice to roll
* d6, +d20 -d100
*/
public int singleRoll(String roll) {
int di = roll.indexOf('d');
if (di == -1) //case where has no 'd'
return Integer.parseInt(roll);
int diceSize = Integer.parseInt(roll.substring(di + 1)); //value of string after 'd'
int result = rand.nextInt(diceSize) + 1; //roll the dice
if (roll.startsWith("-")) //negate if nessasary
result = -result;
return result;
}

Messed up checks?

Just a brief description of what I am doing - I have random equation generator and buttons with all the digits. In order to answer the question the user has to click the corresponding buttons to form the question(digits are written from left to right) e.g. 9 + 6 = user clicks 1 and 5. If the answer is correct another equation should come up. The issue I am encountering for now is that SOMETIMES when the answer is a single digit there is no new equation showing up, nor any errors or something. Just nothing happens. Most of the time this occurs is when the answer is "0". Any idea what might be causing this ? Here is part of the code :
public void checkAnswer(){
int answer = question.getAnswer();
if(ansID2==-1){
if(String.valueOf(answer).equals(String.valueOf(ansID1))){
makeEquation();
}
}else{
if(String.valueOf(answer).equals(String.valueOf(ansID1) + String.valueOf(ansID2))){
makeEquation();
}
}
}
ansID2 is set to be -1 so if the answer is only a single digit the second digit place is skipped. ansID's are assigned when the button with the digit is clicked.
checkAnswer is called from a button "Check Answer" with the following code
EventHandler checkHandler = new EventHandler(){
#Override
public void handle(Event arg0) {
checkAnswer();
}
};
ansID2 is set to -1 in the field declaration
I would do this numerically:
public void checkAnswer(){
int answer = question.getAnswer();
int response = ansID1;
if(ansID2 >= 0) {
response = 10 * response + ansID2;
} // else a one-digit response
if (answer == response) {
makeEquation();
}
}
At minimum, that's more efficient than performing all the string manipulation you do in the original code. With that said, I don't see why this version would produce different results from yours. I'm inclined to suppose that your real problem is elsewhere, such as either the answer or the response digits being incorrect.
In particular, you say
ansID2 is set to -1 in the field declaration
but that's sufficient only until the first question with a two-digit answer, which will cause ansID2 to be set to something else. It (and also ans1ID) should be reset when a new equation is created.

Categories

Resources