ActionListener works perfectly after second time it's pressed - actionlistener

entercommand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String userinput = enterword.getText();
String userinput2 = entersecondword.getText();
if (" ".equals(userinput) || " ".equalsIgnoreCase(userinput2)) {
JOptionPane.showMessageDialog(null, "The space is empty please try again");
} else {
enterword.setText(" ");
entersecondword.setText(" ");
System.out.println("test");
JapanesestudiesExcel JE = new JapanesestudiesExcel();
JE.JapanesestudiesExcel(userinput, userinput2);
}
;
}
});
It checks input in the fieldbox the second time the Listener is fired, but the first time it does not work. TO better explain this, when a user enters nothing it doesn't check for an empty string it writes the empty box into excel. The second time the ActionListener is fired it checks perfectly and reports the message back to the user. Why does this occur?

you're testing this for a space, not the empty string:
(" ".equals(userinput) || " ".equalsIgnoreCase(userinput2))
remove the space:
("".equals(userinput) || "".equalsIgnoreCase(userinput2))
Also, this is why it works the second time you click it:
enterword.setText(" ");
entersecondword.setText(" ");
You're setting the field to a space, so it will be true the next time around.

Related

Looking for a simple way for scanner to detect an empty entry ie. just an enter key

I am learning Java and using the scanner to detect and use int values. Everything works fine except that when I press enter without typing in any value I want the app to tell me that it is an invalid entry. Any help greatly appreciated.
My code is below.
int days = 0; // variable to store number of days
boolean isValidDay = false; // detects if the input is a valid number
// create a new scanner
// with the value from the console
Scanner input = new Scanner(System.in);
do
{
try
{
// Print question
System.out.print("Enter the number of days to record rainfall: ");
days = input.nextInt(); // Is it a valid Integer?
if (days <= 0)
{
System.out.println("The input is invalid. Please enter again!");
}
else
{
isValidDay = true;
}
}
catch (InputMismatchException e) // invalid Integer
{
System.out.println("The input is invalid. Please enter again!");
input.nextLine();
}
} while (!isValidDay); // keep repeating till we get a valid number for a day

Android Studio Kotlin show next textview integer

Im trying to create a generator, when i click the start button, the textview gives me a a random number.
This works great,
but i want to show the numbers still i click stop
so it must give me every few secons a new random number from my mutable List.
How could I do this?
My first opinion was, recursive function.
private fun run() {
var x = 0
var randomListe = mutableListOf<Int>()
randomListe.add(Random.nextInt())
x++
for (element in randomListe) {
var x = 0
val zahlInListe = randomListe[x]
// Thread.sleep(1_000)
// I tried while here
textView.text = ("${randomListe[x]} \n das ist die Random Zahl moruk\n")
}
}
You can launch a coroutine block in lifecycleScope for this and you can also remove redundant x for keeping the current index to show the last value, you can use the last method of ArrayList to get the last value in the list
Make changes to your run method and return a Job object from it so you can cancel it later when the user taps on the stop button.
private fun run(): Job {
return lifecycleScope.launch {
while(true){
delay(1000)
var randomListe = mutableListOf<Int>()
randomListe.add(Random.nextInt())
textView.text = ("${randomListe.last()} \n das ist die Random Zahl moruk\n")
}
}
}
Now keep the return job value in a variable, on calling the run method
private var job: Job? = null
job = run()
Call cancel on job when the user taps on the stop button
btnStop.setOnClickListener{
job?.cancel()
}

Notes Window Not Updating on Bill

I am updating the Notes on a Bill via some custom code in a graph extension. My problem is that the window that pops open when you click on the Notes icon in the upper-right corner of the screen does not reflect the changes that I made to the notes in code. If I use the < > buttons to scroll to another Bill and then back to the one that I updated, it shows the changes. So, I'm not sure how to get the notes to refresh.
This is on the AP301000 screen. I have tried Base.Document.View.RequestRefresh(), Base.Document.View.Clear() and calling the Base.Actions.PressSave() after my code changes the note for the Bill.
TIA!
Here's Code:
protected void APTran_RowInserted(PXCache cache, PXRowInsertedEventArgs e)
{
var row = (APTran)e.Row;
if (row == null)
return;
//*********************** copy notes and file attachments from PO lines and header to the Bill **********************************
if ((row.PONbr != null) && (row.POLineNbr != null))
{
POOrderEntry poEntry = (POOrderEntry)PXGraph.CreateInstance(typeof(POOrderEntry));
poEntry.Clear();
POOrder poHeader = poEntry.Document.Search<POOrder.orderNbr>(row.PONbr);
poEntry.Document.Current = poHeader;
POLine poLine = poEntry.Transactions.Search<POLine.lineNbr>(row.POLineNbr);
if (poLine != null)
{
PXNoteAttribute.CopyNoteAndFiles(poEntry.Caches[typeof(POLine)], poLine, cache, row); //// - use this for Notes and Files.
// making of copy of what the note is on the APInvoice at this point because the PXNoteAttribute.CopyNoteAndFiles() below
// will replace what is in the notes with what is in the PO instead of appending.
string oldNote = PXNoteAttribute.GetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
PXNoteAttribute.CopyNoteAndFiles(poEntry.Caches[typeof(POOrder)], poHeader, Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
PXNoteAttribute.SetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current, oldNote);
Base.Actions.PressSave();
string poNote = PXNoteAttribute.GetNote(poEntry.Caches[typeof(POOrder)], poHeader);
if (!string.IsNullOrEmpty(poNote))
{
//string oldNote = PXNoteAttribute.GetNote(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current);
if ((oldNote == null) || !oldNote.Contains(poNote))
{
string newNote = "";
if (string.IsNullOrEmpty(oldNote))
newNote = poNote;
else
newNote = oldNote + Environment.NewLine + poNote;
//These 2 lines will not update the note without the PressSave();
//Guid noteGuid = (Guid)PXNoteAttribute.GetNoteID(Base.Caches[typeof(APInvoice)], Base.CurrentDocument.Current, null);
//PXNoteAttribute.UpdateNoteRecord(Base.Caches[typeof(APInvoice)], noteGuid, newNote);
PXNoteAttribute.SetNote(Base.Caches[typeof(APInvoice)], Base.Document.Current, newNote); // Sets the note but, screen does not refresh.
//Base.Caches[typeof(APInvoice)].Update(Base.Document.Current); //Does not refresh Notes on screen.
//PXNoteAttribute.GetNoteID<APInvoice.noteID>(Base.Caches[typeof(APInvoice)], Base.Document.Current); // Does not update the screen.
//Base.Caches[typeof(Note)].IsDirty = true; /// No Effect.
//Base.Caches[typeof(Note)].Clear(); //this has no effect on refreshing the notes that are seen on the screen.
//Base.Caches[typeof(NoteDoc)].Clear();
//Base.Actions.PressSave(); // blanks out the header if the Bill has never been saved. Does not refresh note on screen.
//Base.Document.View.Clear();
//Base.Document.View.RequestRefresh(); // this wipes out the new note if adding a second PO.
}
}
}
}
}
Here's the fix for this that I deployed. I'm thinking that there is a better way to do this but, seems to be working ok for now. I added this:
[PXOverride]
public void Persist(Action persist)
{
persist();
APInvoice invoice = (APInvoice)Base.CurrentDocument.SelectSingle();
if (invoice.Status == "H")
throw new PXRedirectRequiredException(Base, "Reloading Notes...");
}
So, I overrode the Persist() in order to refresh the page but, I only do that if the Bill is still on Hold. This refreshes the Notes that are shown on the screen.

How to stop onItemSelected() from firing off multiple times after a selection of an item was made?

I've seen another similar thread, but I wasn't able to resolve my issue with the given answers.
EXPLANATION OF MY GOALS:
I have 4 spinners, each has its own ArrayList of strings assigned to it via an adapter. All of these arrays contain the same values at the beginning.
I want to remove the selected value (eg. "item" in spinner1) from all the other spinners (remove "item" from spinner2, 3 and 4) when it is selected.
PROBLEM:
When I select an item for the first two or three times from different spinners (the number of selections needed to reproduce the problem varies) the onItemSelected() method gets called multiple times (the number of callings is greater than the number of actual -user- selections made).
QUESTION:
How to prevent the calling of onItemSelected(); at unnecessary times. I want it to be called only when the actual user makes a selection in one of the spinners and only call it once when that does happen.
If you want to try to help me out and you need more code / images of the problem on the device itself, please, say so.
Here is my whole onItemSelected() method:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (inCorrection == false)
{
s1 = spinner1.getSelectedItemPosition();
s2 = spinner2.getSelectedItemPosition();
s3 = spinner3.getSelectedItemPosition();
s4 = spinner4.getSelectedItemPosition();
testcount++;
switch(parent.getId())
{
case R.id.v1_q1_s1:
if((position != AdapterView.INVALID_POSITION) && (spinner1.getSelectedItem().toString() != "Default---"))
{
findLists(myList2, myList3, myList4, spinner1.getSelectedItem().toString());
if(returnChecks(0) != "Default---")
{
myList2.add(returnChecks(0));
myList3.add(returnChecks(0));
myList4.add(returnChecks(0));
}
addChecks(0, (spinner1.getSelectedItem().toString()));
}
else
{
if(position != AdapterView.INVALID_POSITION)
{
myList2.add(returnChecks(0));
myList3.add(returnChecks(0));
myList4.add(returnChecks(0));
addChecks(0, (spinner1.getSelectedItem().toString()));
}
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
adapter4.notifyDataSetChanged();
Toast.makeText(Vprasalnik1.this, myList1.toString()+"\n"+myList2.toString()+"\n"+myList3.toString()+"\n"+myList4.toString()+"\n"+checks.toString(), Toast.LENGTH_LONG).show();
break;
case R.id.v1_q1_s2:
if((position != AdapterView.INVALID_POSITION) && (spinner2.getSelectedItem().toString() != "Default---"))
{
findLists(myList1, myList3, myList4, spinner2.getSelectedItem().toString());
if(returnChecks(1) != "Default---")
{
myList1.add(returnChecks(1));
myList3.add(returnChecks(1));
myList4.add(returnChecks(1));
}
addChecks(1, (spinner2.getSelectedItem().toString()));
}
else
{
if(position != AdapterView.INVALID_POSITION)
{
myList1.add(returnChecks(1));
myList3.add(returnChecks(1));
myList4.add(returnChecks(1));
addChecks(1, (spinner2.getSelectedItem().toString()));
}
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
adapter4.notifyDataSetChanged();
Toast.makeText(Vprasalnik1.this, myList1.toString()+"\n"+myList2.toString()+"\n"+myList3.toString()+"\n"+myList4.toString()+"\n"+checks.toString(), Toast.LENGTH_LONG).show();
break;
case R.id.v1_q1_s3:
if((position != AdapterView.INVALID_POSITION) && (spinner3.getSelectedItem().toString() != "Default---"))
{
findLists(myList2, myList1, myList4, spinner3.getSelectedItem().toString());
if(returnChecks(2) != "Default---")
{
myList2.add(returnChecks(2));
myList1.add(returnChecks(2));
myList4.add(returnChecks(2));
Toast.makeText(Vprasalnik1.this, "before: "+returnChecks(2), Toast.LENGTH_LONG).show();
}
addChecks(2, (spinner3.getSelectedItem().toString()));
Toast.makeText(Vprasalnik1.this, "after: "+returnChecks(2), Toast.LENGTH_LONG).show();
}
else
{
if(position != AdapterView.INVALID_POSITION)
{
myList2.add(returnChecks(2));
myList1.add(returnChecks(2));
myList4.add(returnChecks(2));
addChecks(2, (spinner3.getSelectedItem().toString()));
}
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
adapter4.notifyDataSetChanged();
Toast.makeText(Vprasalnik1.this, myList1.toString()+"\n"+myList2.toString()+"\n"+myList3.toString()+"\n"+myList4.toString()+"\n"+checks.toString(), Toast.LENGTH_LONG).show();
break;
case R.id.v1_q1_s4:
if((position != AdapterView.INVALID_POSITION) && (spinner4.getSelectedItem().toString() != "Default---"))
{
findLists(myList2, myList3, myList1, spinner4.getSelectedItem().toString());
if(returnChecks(3) != "Default---")
{
myList2.add(returnChecks(3));
myList3.add(returnChecks(3));
myList1.add(returnChecks(3));
}
addChecks(3, (spinner4.getSelectedItem().toString()));
}
else
{
if(position != AdapterView.INVALID_POSITION)
{
myList2.add(returnChecks(3));
myList3.add(returnChecks(3));
myList1.add(returnChecks(3));
addChecks(3, (spinner4.getSelectedItem().toString()));
}
}
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
adapter4.notifyDataSetChanged();
Toast.makeText(Vprasalnik1.this, myList1.toString()+"\n"+myList2.toString()+"\n"+myList3.toString()+"\n"+myList4.toString()+"\n"+checks.toString(), Toast.LENGTH_LONG).show();
break;
}
correctSelection();
}
}
At the end of the above code there is a function I call named correctSelection();, that corrects the selection of all spinners, because it doesn't work correctly otherwise - it looks like this:
void correctSelection()
{
inCorrection = true;
spinner1.setSelection(myList1.lastIndexOf(returnChecks(0)));
spinner2.setSelection(myList2.lastIndexOf(returnChecks(1)));
spinner3.setSelection(myList3.lastIndexOf(returnChecks(2)));
spinner4.setSelection(myList4.lastIndexOf(returnChecks(3)));
inCorrection = false;
}
/*it sets the position of all spinners to the last "saved"
(current) item selected, so it corrects the possible index offset that occurs otherwise
(returnChecks(); returns the last item selected from an array in a string format)
PS: To avoid the calling of onItemSelected() in case of programmatically setting the selection
of spinners, I've input a boolean flag (variable "inCorrection"), which is set to false before the
selections are made by "the application" and then set back to false when the code gets run.
*/
To prevent onItemSelected() from being called when you set up the spinner, you can do it like this:
spinner.setOnItemSelectedListener(null);
adapter.notifyDatasetChanged();
spinner.setSelection(0, false);
spinner.setOnItemSelectedListener(onItemSelectedListener);
Explanation:
The framework fires the onItemSelected event when a change in the selection has occurred. It detects a change by registering the current selected position and the previous selected position (mSelectedPostion and mOldSelectedPosition).
When you call notifyDatasetChanged the framework performs various checks to see if the previous selection can be found, so onItemSelected may or may not be called when the spinner is laid out.
By calling setSelection(0, false) these positions are set to 0, possibly detecting a change, but since onItemSelectedListener is null, onItemSelected wont be fired. Position 0 is selected because I guess the "Default---" value is the first position in the list. You can choose another position if you like.
When the spinner is later laid out there is no change, so onItemSelected wont be fired here either.
Note that this has been established by debugging on API level 19 (Android 4.4 KitKat). I don't know if it works on other versions, and I haven't been able to find anything in the documentation to support it.
You can stop the spinner from firing prior to the user making a selection via the optional animation field in the setSelection method. Be sure to order your code this way:
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yourList);
spinner.setAdapter(spinnerAdapter);
spinner.setSelection(0, false); //stops spinner from firing prior to user selection
as explained by user1801374 , I made the fix for my case. Just make sure before and after selection index remains same in order to not to invoke the onItemSelected again.
private int spinnerIndex = 0;
spinner.setSelection(spinnerIndex, false);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{ public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
// Your code here
//I was detaching and reattaching one fragment which was calling the onItemSelected multiple times, recursively.
spinnerIndex = i;
spinner.setSelection(spinnerIndex, false);
return;
}
public void onNothingSelected(AdapterView<?> adapterView) {
// Your code here
return;
}
}

Menu driven palindrome tester getting stack Overflow error

I'm doing this for a class, and I'm really not terribly awesome at this as I'm over a decade out of practice. I'm trying to write a program that displays a menu so the user can choose between methods of determining if it's a palindrome.
It then needs to redisplay the menu once it has completed the test. I'm getting a stack overflow error in the isPalindrome method since I combined the 2 classes into one class, which I thought would fix another problem I was having with the output! Any thoughts or directions I can take?
import java.util.Scanner;
public class PalHelper
{
public String pal;
public void MenuList()
{
System.out.println("How would you like to check your phrase?");
System.out.println("1. Check the first letter like it's the last letter - Leave no phrase unturned!");
System.out.println("2. I Prefer my Palindromes have the gentle treatment");
System.out.println("3. We're done here");
System.out.print("Selection: ");
}
public PalHelper()
{
Scanner decision = new Scanner(System.in);
MenuList();
switch (decision.nextInt())
{
//to access the character by character method of determination
case 1:
System.out.print("Enter Phrase to Test, the Hard Way:");
Scanner keyboard1 = new Scanner(System.in); //declares scanner variable for user entry
String UserInput1 = keyboard1.next();//Phrase variable
Boolean test1 = isPalindrome(UserInput1);
if (test1 == true){
System.out.println(UserInput1+" is a palindrome. That doesn't make you smart.");
}
else {
System.out.println(UserInput1+" is a not palindrome. Why don't you think a little harder and try again.");
}
System.out.println("..\n..\n..\n");
keyboard1.close();
new MenuList();
break;
//to access the string buffer method of determination
case 2:
System.out.print("Thank you for choosing the gentle way, please enter your phrase:");
Scanner keyboard2 = new Scanner(System.in); //declares scanner variable for user entry
String UserInput2 = keyboard2.next();
Boolean test2 = isPalindrome2(UserInput2);
if (test2 == true){
System.out.println(UserInput2+" is a palindrome. Congratulations! You are so wonderful!");
}
else {
System.out.println(UserInput2+" is a not palindrome. It's ok, I'm sure you'll get it next time.");
}
System.out.println("..\n..\n..\n");
keyboard2.close();
new MenuList();
break;
//exit menu
case 3:
System.out.println ( "Too bad – I hid a boot!" );
break;
//response to input other than 1,2,3
default:
System.out.println ( "No sir! Away! A papaya war is on." );
System.out.println("..\n..\n..\n");
new MenuList();
break;
}// close switch
}//close pal helper
public void Palindrome(String UserInput) {
}
public boolean isPalindrome(String UserInput) {
pal = UserInput.toUpperCase();
if (pal.length() <= 1) {//one character, automatically a palindrome
return true;
}
char start = pal.charAt(0);
char end = pal.charAt(pal.length()-1);
if (Character.isLetter(start) &&
Character.isLetter(end)) {//check if first and last characters match
if (start != end) {
return false; //if the beginning & ending characters are not the same it's not a palindrome
}
else {
Palindrome subpal = new Palindrome(pal.substring(1,pal.length()-1));
return subpal.isPalindrome(); //check middle dropping start and end letters
}
}
else if (!Character.isLetter(start)) {
Palindrome subpal = new Palindrome(pal.substring(1));
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
}
else {
Palindrome subpal = new Palindrome(pal.substring(0,pal.length()-1));
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
}
}//close isPalindrome
public boolean isPalindrome2(String UserInput){
pal = UserInput.toUpperCase();
pal = pal.replaceAll("\\W", "");//gets rid of space and punctuation
StringBuffer check = new StringBuffer(pal);//reverses pal string and creates new stringbuffer for check
check.reverse();
if (check.toString().equals(pal)){//checks for equality between pal and it's reverse
return true;
}
else {
return false;
}
}//close isPalindrome2
public static void main (String[]args)
{
new PalHelper();
}//close main
}//close class
Aside from my comment above, there is a problem that I noticed: in some cases, you construct a new Palindrome instance with the substring, but pass the full string while recursing to the isPalindrome() method. This causes the recursion to never terminate (which also makes your code hard to follow).
Your example is missing something, the following line has missing closing brackets:
Palindrome subpal = new Palindrome(pal.substring(1,pal.length()-1);
Your comments dont seem to match the code:
return subpal.isPalindrome(pal); //check if first letter is a letter, drop if not
Try adding Output to the Method isPalindrome() or debug it. You are probably not calling it with the right Strings and end up looping over the same Strings over and over.
public boolean isPalindrome(String UserInput) {
System.out.println(UserInput);
...
Edit: If your code really is exaclty like you posted then vhallac is right, you call isPalindrome() with the full String.

Resources