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.
Related
I am currently working on a game where players are supposed to solve for X + Y with selection of 3 buttons (1 of which is answer) and a "Next" button to go to the next question (by replacing values of components into the next question's). However, I am not able to tally the answers because my tested selection (Button) is always testing the values of the next question
To give a little context,
questionCategories is an ArrayList of ArrayList with different levels
e.g. questionCategories.get(selectedLevel) returns ArrayList of different arithmetics
jumbleOptions populates 3 buttons with correct and incorrect answers which are housed in options
I'm having a situation where when answering Question 1, the shown option values belongs to Question 1, but the tested values (in test) are from Question 2.
e.g.
Qn1: 3 + 5 - A: 2, B: 8, C: 4
Qn2: 8 + 2 - A: 10, B: 11, C:12
When I attempt Qn1 on B and click "Next" to go to the next question (and test for correctness), Instead of testing B:8 my program ends up testing B: 11 instead. I have tried to Log the captured values of each Button and Question's answer but they are all correct and I am not sure where did I go wrong.
The code snippet is within onViewCreated, the first question is initialized to display because of placeholder text in the original element. I'm sorry if the code snippet does not make much sense, trying to keep it short so it's (hopefully) more readable.
// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));
do {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
// Increment question number related variable
numQnAnswered++;
// Replace displayable elements with next question
//Question Number
questionNumber.setText("Question " + String.valueOf(numQnAnswered));
questionTitle.setText(q.toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));
boolean test = checkAnswer(String.valueOf(q.getAnswer()),
options.get(SELECTED_OPTION).getText().toString());
Log.d("Answer Correctness", String.valueOf(test));
}
});
counter++;
} while (counter < NUMBER_OF_QNS);
Let's simulate the scenario:
First question is set up manually, and next question is loaded based on button click. I assume numQnAnswered is 0 and you're getting the answer from your Question object of numQnAnswered th position, right?
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
As your codes say so.
Notice here, carefully:
// Increment question number related variable
numQnAnswered++;
Now the problem however is, the answer is validated inside button click, I think you've forgot the fact that the first question was set up manually... & before checking the answer for that one you've incremented the numQnAnswered variable, thus your question is one step behind your answer. Hope it make sense.
Just decrement the numQnAnswered variable after the validation of current question.
// Initialize first question to display
questionNumber.setText("Question " + String.valueOf(qnNumDisplay));
questionTitle.setText(((questionCategories.get(selectedLevel)).get(0)).toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(0)));
do {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Question q = (questionCategories.get(selectedLevel)).get(numQnAnswered);
// first we need to check answer of previous question
boolean test = checkAnswer(String.valueOf(q.getAnswer()),
options.get(SELECTED_OPTION).getText().toString());
Log.d("Answer Correctness", String.valueOf(test));
// Increment question number related variable
numQnAnswered++;
// Replace displayable elements with next question
//Question Number
questionNumber.setText("Question " + String.valueOf(numQnAnswered));
questionTitle.setText(q.toString());
jumbleOptions(((questionCategories.get(selectedLevel)).get(numQnAnswered)));
}
});
counter++;
} while (counter < NUMBER_OF_QNS);
I'm using a JMenu (named Count) with four JMenuItems (named Inc, Dec, Reset, Quit). When I click on any of the menuitems I want it to display the integer in the JTextArea. For example, everytime I click on Inc it should show the integers vertically listed starting from 0. The issue right now is that when I press the Dec menuitem its not taking the last number listed.
I tried to use the getText method but I keep getting a NumberFormatException and saying that the input string is a bunch of numbers e.g.:
0
1
2
3
4
From what I can tell, I am aware that I need to be able to keep track of the last number in a way that all menuitems (aside from the quit menuitem) can access it and change it. I just have no idea how to do it.
Here is one of the ways that I've tried where it gives me the error I mentioned above.
//newLine = "\n";
public void actionPerformed(ActionEvent ae) {
String ac = ae.getActionCommand();
if(ac.equals("Inc")) {
jta.append(count + newLine);
count++;
}
else if(ac.equals("Dec")) {
count = Integer.parseInt(jta.getText());
countText = Integer.toString(count);
jta.append(countText + newLine);
count--;
}
else if(ac.equals("Reset")) {
jta.selectAll();
jta.replaceSelection("0");
count = 0;
}
else if(ac.equals("Quit")) {
System.exit(0);
}
}
I was expecting
0
1
2
3
4
3
2
1
to be displayed in the TextArea when I click on Inc and Dec
But instead its just
0
1
2
3
4
and then I get a NumberFormatException saying that the input string is:
0
1
2
3
4
If possible, I would like the input string to be just the last integer in the textarea.
I hope this makes sense. This is my first time making a post on stackoverflow.
When you get the text, it has returned "0 1 2 3 4" which cannot be parsed an integer, therefore the exception.
If you want to get the last integer in the text field, you need to retrieve the text and find the substring that represents the last integer. Look at the javadocs for String, especially the lastIndexOf(), split(), and substring() methods.
If you have placed each integer on a separate line, and have kept track of the last number entered in an instance variable "count", then you just need to call jta.append( (count-1) + newLine); without having to retrieve the text at all.
Note that your code does not save the last number entered - it saves (last+1)
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.
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.
Doing this for my project, using jFrame.
My problem is, when I input first:1 , Second: 2 , third: 3
and I clicked view stack, and the problem shows [ 1 , 2 , 3 , 0 , 0 , 0 . . . ]
I think the view should be [ 3 , 2 , 1 , 0 , 0 . . . .]
what what I understood about push.
code used :
// Global Variable
int[] myStack = new int [10];
int top = -1;
// Push Button
if ( top == 9){
JOptionPane.showMessageDialog(null, "Stack Full!");
}else{
int val = Integer.parseInt(pushtxt.getText());
top++;
myStack[top] = val;
pushtxt.setText("");
}
}
// View Stack Button
if (top == -1){
JOptionPane.showMessageDialog(null, "Stack Empty!");
}else{
viewtxt.setText("");
for (int x=0; x<=9; x++){
viewtxt.setText(viewtxt.getText()+" "+ myStack[x]);
}
}
I think you're misunderstanding the way a stack works. More specifically, the algorithm you use to display the stack is incorrect. In your case, you start at the bottom of the stack (where x=0) and work your way towards the top (actually, beyond the top, where x=9). This is why your output seems reversed to you (it's also full of zeros that you shouldn't be printing).
When displaying the stack, you should start at the top (x=2) and work your way towards the bottom (x=0). If you do things this way, then the output will be correct.
Stacks are FiLo, First in, last out. Generally stacks are used in a manner where you push items (the first being the bottom of the stack) and they keep on stacking. When you need to get values off of the stack you pop, going back in reverse order.
So the order you entered for data would store as:
1,2,3
bottom -> top
Your data is correct, it is as it should be.
So next you'll want to write a pop function, where you grab the value at the top of the stack and then decrement the top variable.
Popping your stack one at a time would return in the following order:
3
2
1
From what you were describing, I think perhaps you were going to pop from the front of the stack? If that is what you want to do, you would have to shift all of your values every-time you pushed a new value. What you currently have now is better code than shifting all your values on every push =]
You are on the right track.
EDIT I have not used swing in a while, but hopefully this will lead you in the right direction (I looked at some old code to make sure my syntax was correct, have not tested though). To answer the question you asked in my comment, your code would look something similar to the following for the pop function and setting the text for the popTextField
your pop function should look something like the following:
/**
* The code for the button press could be as simple as follows
*/
popBtn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
try{
popTextField.setText(popStack);
}catch(IndexOutOfBoundsException e){
popTextField.setText("The stack is empty");
}
}
});
the pop function can be really simple. You do not need to use exceptions - but it is good practice.
/**
* Simple Pop function
*/
private int popStack(){
if(top >= 0){
return myStack[top--];
}else{
throw new IndexOutOfBoundsException("The stack is empty");
}
}