Adding to ArrayList from EditText - java

I am trying to implement a button that saves integers entered into an EditText and save them into an ArrayList. I declared my ArrayList globally in my class and am calling it inside of my OnClickListener method. I am unsure whether or not I am saving to this ArrayList because I am unable to display what I have saved in said ArrayList.
My declaration of the list is;
ArrayList<String> savedScores = new ArrayList<String >();
This is what I am using to save to my ArrayList;
`savedScores.add(input1.getText().toString());`
Now, in my OnClickListener method, I have a button that saves user input into the ArrayList (or so I am hoping), and another to display what I have saved. However, when I click on the "editScore" button, the TextEdit is cleared as if I have nothing saved in my ArrayList. This is simply a test to see if I am properly saving to my array and any help would be much appreciated! Thank you.
switch (view.getId()) {
case R.id.buttTotal:
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
break;
} else {
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
output1.setText("Your score is : " + Integer.toString(sum));
input1.setText(""); //Clear input text box
//SAVE TO THE ARRAYLIST HERE
savedScores.add(input1.getText().toString());
break;
}
case R.id.allScores: //CHANGE THIS TO AN EDIT BUTTON, ADD A HOLE NUMBER COUNTER AT TOP OF SCREEN!!!!!
output1.setText("you messed up");
break;
case R.id.editScore: //Need to set up Save Array before we can edit
output1.setText(savedScores.get(0));
break;
}

Because you are saving empty values into your ArrayList. See here
input1.setText(""); //Clear input text box
//SAVE TO THE ARRAYLIST HERE
savedScores.add(input1.getText().toString());
The value of input1 is empty. Clear the input after you saved it to the array.

Related

How to update data from listview if the condition were met android java

Hi Iam creating this app were you input Name and it automatically put the Time-inon the listview with current time. Now, if the user were to put the same Name, the system then recognized it to avoid duplication.
Here is the code for condition
getTime();
String fnlAddName = finalTextName+"\n"+formattedDate+"\n"+strTime;
if (names.indexOf(finalTextName) > -1){
//the system recognized the same input
String beforeName = listView.getItemAtPosition(position).toString();
names.add(beforeName+"\n"+strTime);
myAdapter.notifyDataSetChanged();
}else{
names.add(fnlAddName);
myAdapter.notifyDataSetChanged();
dialog.cancel();
position = position+1;
}
Now, I already achieved to detect same input from the user. What I want now is, I want to take that same data from the list (with also the time) and add another current time. So the list must update from "Name+1stCurrentTime" to "Name+1stCurrentTime+2ndCurrentTime"
Your code should look something like this
if (names.indexOf(finalTextName) > -1){
//the system recognized the same input
int index = names.indexOf(finalTextName);
names.set(index, names.get(index) + "\n" + strTime);
myAdapter.notifyDataSetChanged();
}else{
names.add(fnlAddName);
myAdapter.notifyDataSetChanged();
dialog.cancel();
position = position+1;
}
With the indexOf method you can get the position of the list that contains the name, then we replace it, I hope this helps you.

Selecting items inside jListbox Java Netbeans [duplicate]

This question already exists:
How to selected items in a listbox Java Netbeans [closed]
Closed 2 years ago.
Morning all,
I am currently working on a project that involves selected an item from a list box.
The format I am following for the items in the list box is as follows:
(airline name)#(maximum weight)kgs.
My first issue comes with trying to get the item from the list box. I have tried multiple things such as list.getSelectedIndex(); and using a for loop to run through the indexes to try and compare "i" to one of the Airline names but to no avail.
Secondly, do you guys have any suggestions on how I would extract the maximum weight section from my String(SAA#25kgs). My String Handling/Manipulation isn't that great and I would appreciate any suggestions. My first thought was to use .split(), but then I would get the 25kgs as well.
The list box I am using looks like this:
https://gyazo.com/328ddeb9b7888821cfe74fecb551dd08
Kind regards IzzVoid,
To get the selected value from the JList you would do something like this:
String stringItem = jList1.getSelectedValue().trim();
To get the weight from the selected list item:
// Is something in JList selected.
if (jList1.getSelectedIndex() != -1) {
// Yes...Get the selected item from JList.
String stringItem = jList1.getSelectedValue().trim();
System.out.println("Selected List Item: " + stringItem); //Display it.
// Split the JList item based on the Hash character into a String Array.
String[] itemParts = stringItem.split("#");
// Are there two elements within the Array?
if (itemParts.length > 1) {
// Yes...Then the 2nd element must be the weight
String item = itemParts[0]; // Get ite related to weight
System.out.println("Item: " + item); // Display item
String stringWeight = itemParts[1]; // get weight related to item
System.out.println("Weight: " + stringWeight); // Display weight
// Convert weight String to double data type...
// Remove everything not a digit and convert to double.
double weight = Double.valueOf(stringWeight.replaceAll("[^\\d]", ""));
System.out.println("Weight (as double type): " + weight); // Display weight
}
else {
// No...there is only a single element - Assume No Weight is available!
System.out.println("No Weight Available!");
}
}
// No...Nothing appears to be selected in JList.
else {
System.out.println("Nothing selected!");
}

Storing text as an arraylist from JTextArea

I need to create a program to store all words in an array list. Then check the user input from the textfield to see if it starts with anything other than numbers and punctuation. Otherwise it will need to display an error and prvent the string to be added to the arraylist and display an appropriate error.
https://pastebin.com/8UwDm4nE
Heres the ActionEvent listener that contins the code to check that. Im not really sure how to get it working.
#Override
public void actionPerformed(ActionEvent e) {
for(int i = 0; i < 1; i++) {
String str = tf.getText(); // MUST BE STORED ON AN ARRAY LIST
ta.append(str + "\n"); // Append the text on new line each
if(str.startsWith(String.valueOf(nums))) { // Check input for a number at the start
error.setText("Error: Word starts a number. Please try again!");
error.setForeground(Color.RED);
ta.append("");
} else if (str.startsWith(String.valueOf(punct))) { // Check if input contains a punctuation at the start
error.setText("Error: Word starts with an illegal character. Please try again!");
error.setForeground(Color.RED);
ta.append("");
}
}
}
I'm going to rephrase your problem a bit as clarification, please correct me if I'm misunderstanding.
You have a text field and a text area. You want a user to type a word into the text field and submit it. If that word starts with a number or punctuation, then indicate an error to the user. Otherwise, add it to the text area (on a new line) and the inner ArrayList.
To solve this problem, there are a couple things you'll need:
An ArrayList<String> that is a class member variable where you can store your words
An event handler that handles the button click.
The event handler should:
Parse the string from the text field (using getText(), as you already are).
Do the error checks you're already doing.
If neither of the error conditions are hit (so add an else clause for this), add the word to the text area (which you're already doing) and add it to the ArrayList.
Hopefully this helps you get a clearer idea of how to approach the problem. If not, please post a code sample of what you tried and what error you're specifically running into.
EDIT:
Here is some pseudocode for your if-else error-handling block of code, assuming you declare a new ArrayList to hold your words as a class member:
// as class member variable
List<String> wordList = new ArrayList<>();
// word handler code
if (str starts with a number) {
// handle error
} else if (str starts with punctuation) {
// handle error
} else {
ta.append(str + "\n");
wordList.add(str);
}

Passing the Iteration Index of a For Loop Into the Argument of a Method

First Java program. I'm building a flashcard app for fun / self-learning, and I haven't yet figured out how to flip the card to show the back.
ArrayList (called ready) contains objects of my Flashcard class.
One of Flashcard's methods is showFront.
In MainProgram.java I'll iterate through the ArrayList, calling this method at each iteration in order to show the front of the flashcard, and then wait for keyboard input in order to decide what to do next:
MainProgram.java:
ArrayList<Flashcard> ready = new ArrayList<Flashcard>();
ArrayList<Flashcard> entireDeck = new ArrayList<Flashcard>();
// Create ten flashcards and add them to the pile "entireDeck"
for(int counter = 0; counter < 10; counter++) {
Flashcard FC = new Flashcard();
entireDeck.add(FC);
}
(entireDeck.get(0)).addData(0,"A little","Un poco");
Flashcard.java:
class Flashcard {
public int cardNumber;
public String word;
public String translation;
// Add data to a flashcard
public void addData(int cardNumber, String word, String translation){
this.cardNumber = cardNumber;
this.word = word;
this.translation = translation;
}
public void showFront(int index) {
System.out.println("Card #:\t\t" + cardNumber);
System.out.println("Word:\t\t" + word + "\n\n");
System.out.println("1) Replay audio\t 2) Flip card\t 3) Skip\n");
Scanner nav = new Scanner(System.in);
int userInput = nav.nextInt();
switch (userInput) {
case 1:
System.out.println("Playing audio");
break;
case 2:
System.out.println("Flipping card");
showBack(**what to put here?**);
break;
case 3:
System.out.println("Next card...");
break;
default:
System.out.println("Invalid entry. Come back soon!\n");
break;
}
}
public void showBack(int index) {
System.out.println("Card #:\t\t" + cardNumber);
System.out.println("Translation:\t\t" + translation + "\n\n");
System.out.println("1) Replay audio\t 2) Flip card\t 3) Skip\n");
}
}
A for loop in MainProgram.java was used to add flashcards to the ready deck - I'm just removing most of my code to focus on the issue I'm having.
The console correctly displays the front of the card:
Console output showing current card:
And of course it shows the next card in sequence because I chose to break out of every switch case until I figure out how to correctly pass the right argument into showBack():
Console output showing next card:
Again, stripping out unnecessary code for clarification / brevity.
Correct me if I'm wrong but I can't take the variable i from the loop in MainProgram.java and use it as the argument in showBack() because i is not a global variable. I think that I just need to find the current iteration of that for loop and use it as showBack's argument in order to show the back of that card.
I do realize that eventually I'll have to deal with the scanner memory leak caused by not using nav.close().
I have a feeling this is such an easy solution.
**Edit: **I should be using pointers? How can I pass the index of a for loop as the argument for pthread_create

How to remove the last character from TextView in Android? [duplicate]

This question already has answers here:
How to remove the last character from a string?
(37 answers)
Closed 7 years ago.
I am creating a calculator app for a class and I have everything working except the "BackSpace" Button. The only information that I can find on manipulating the TextView is using the SetText method to reset the TextView to either null or just an empty string. What I need to do though is remove the last number entered into the calculator ex: if the number 12 is entered in and the backspace button is pressed it will delete the 2 but leave the 1. I decided to only include my "onClick" method as its the only method relevant to this question all the calculations are done in another method. Thanks!
public void onClick(View v) {
// display is assumed to be the TextView used for the Calculator display
String currDisplayValue = display.getText().toString();
Button b = (Button)v; // We assume only buttons have onClickListeners for this App
String label = b.getText().toString(); // read the label on the button clicked
switch (v.getId())
{
case R.id.clear:
calc.clear();
display.setText("");
//v.clear();
break;
case R.id.plus:
case R.id.minus:
case R.id.mult:
case R.id.div:
String operator = label;
display.setText("");
calc.update(operator, currDisplayValue);
break;
case R.id.equals:
display.setText(calc.equalsCalculation(currDisplayValue));
break;
case R.id.backSpace:
// Do whatever you need to do when the back space button is pressed
//Removes the right most character ex: if you had the number 12 and pressed this button
//it would remove the 2. Must take the existing string, remove the last character and
//pass the new string into the display.
display.setText(currDisplayValue);
break;
default:
// If the button isn't one of the above, it must be a digit
String digit = label;// This is the digit pressed
display.append(digit);
break;
}
}
Use Substring
It will allow you to replace / remove characters by index (in your case it will be the last index of the string)
NumberEntered = NumberEntered.substring(0, NumberEntered.length() - 1);
If you have a number entered 1829384
Length is 7, index will start at 0
When substringed it will be from 0 to (7-1) thus new string will be 182938

Categories

Resources