How to add a text to the remaining text in android - java

I want to add text to the EditText without losing the previous text.
Ex: when typing 74, i want to add the "4" to the text box without erasing the number "7" entered before.
public void add4()
{
res = (EditText)findViewById(R.id.editText1);
if(res.getText().toString() == "0")
{
res.setText("4");
}
else
{
// add number 4 to the remaining string
}
}

You can use the append method to append to existing text.
res.append("4");
http://developer.android.com/reference/android/widget/TextView.html#append(java.lang.CharSequence)
(As a side note, don't use == to compare strings, use .equals())

Try this:
I used the .equals method on a string object to avoid the NullPointerException that may happen if the object is null or not a string.
public void add4() {
res = (EditText)findViewById(R.id.editText1);
if( "0".equals(res.getText().toString()) )
{
res.setText("4");
}
else
{
res.append("4");
}
}

res.append("4"); or you can use res.setText(res.getText() + "4");

Related

Check exact word in scrabble words list

I have a Scrabble Clock with a verification tool inside.
The verification word space looks in green or red if the word that I check is in the list.
The thing is, if I use sbuffer.toString().contains, and write a word like ABA, the word space looks in green though ABA is not in the list, but ABAC, ABACA are in the list.
I would like to know how I can implement a condition in my code to check the exact complete word.
I've researched regex, boundary and matches, but I couldn't find a line code that words in my code.
Here is my code until now.
public class MainActivity extends AppCompatActivity {
TextView textView;
TextView textInV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.texto_1);
textView.setMovementMethod(new ScrollingMovementMethod());
textInV = findViewById(R.id.textIn);
String data = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(R.raw.fruits);
BufferedReader reader = new BufferedReader((new InputStreamReader(is)));
if (is != null)
{
try
{
while((data =reader.readLine())!=null)
{
sbuffer.append((data + "\n"));
}
is.close();
}
catch (Exception e){ e.printStackTrace();}
}
textView.setText(sbuffer);
}
}
The contains method on a string tests whether the target is contained as a substring; if ABAC is contained as a substring then so is ABA, since ABA is a substring of ABAC and hence it is also a substring of any string which ABAC is a substring of. Therefore, it is not logically possible for the String.contains method to return true for ABAC and false for ABA.
You want to test if the target is one of the elements of a collection of strings, so you should use contains on a collection of strings, not on a string. The best choice is a HashSet, since this performs membership tests in O(1) time on average.
> import java.util.*;
> Set<String> allowed = new HashSet<>();
> allowed.add("ABAC");
> allowed.add("ABACA");
> allowed.contains("ABA")
false
> allowed.contains("ABAC")
true
As #Ashutosh KS has already mentioned, String.contains is not really what you are looking for in this case: You want to check if two strings are identical, not if one contains the other.
The Java String class contains a few methods that you can use to compare the content of two strings, of which you can choose accordingly to match your exact use case:
contentEquals(CharSequence cs) and contentEquals(StringBuffer sb) both check if the passed string representation's content matches the current one.
equals(Object str) is similar to contentEquals in that it makes an exact comparison between both strings, however it also checks to make sure that the passed object is in fact a string.
equalsIgnoreCase(String anotherString), as the name implies, will do a check while ignoring the string case.
These are the 'proper' ways to compare two strings exposed by the native API, so while it is absolutely possible to use other methods, it is a good idea to stick to these.
StringBuffer's contains() check if the given string is a substring of the text in the sbuffer. That means, it will output true for searching "ABC" in "ABC", "ABCBC", "ZABC", "ZABCBC"...
If you want to search for a complete word in the sbuffer, then you can look for "\n" + "ABC" + "\n" since you're adding "\n" when adding words to sbuffer: sbuffer.append((data + "\n"));. But, you must also initialize sbuffer with "\n": StringBuffer sbuffer = new StringBuffer("\n");.
sbuffer.toString().contains("\n" + "ABC" + "\n"); // this will do the trick
Test code:
class Main {
public static void main(String[] args) {
StringBuffer sbuffer = new StringBuffer("\n");
StringBuffer sbuffer2 = new StringBuffer("\n");
sbuffer.append("ABC" + "\n");
sbuffer.append("ABCBC" + "\n");
sbuffer.append("ZABC" + "\n");
sbuffer.append("ZABCBC" + "\n");
System.out.println("Is ABC in sbuffer = " + sbuffer.toString().contains("\n" + "ABC" + "\n"));
sbuffer2.append("ABCBC" + "\n");
sbuffer2.append("ZABC" + "\n");
sbuffer2.append("ZABCBC" + "\n");
System.out.println("Is ABC in sbuffer2 = " + sbuffer2.toString().contains("\n" + "ABC" + "\n"));
}
}
Test output:
Is ABC in sbuffer = true
Is ABC in sbuffer2 = false
Now i have this, and works, but i have a file with the words, and i would like to add the files in the diccionario.
But i don't know how to read the file. I have try bufferread, but i need try/catch, and not works....
Some other solutions....
Thanks
boton2.setOnClickListener(new View.OnClickListener()
{
String content;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View view)
{
HashSet<String> diccionario = new HashSet<String>();
//Adding elements to HashSet
diccionario.add("CASA");
diccionario.add("ABAC");
if(diccionario.contains(textIn.getText().toString().toUpperCase()))
{
textIn.setBackgroundColor(Color.GREEN);
}
else
{
textIn.setBackgroundColor(Color.RED);
}
}

How to remove last line of TextView?

I am trying to remove\replace last line of a TextView, but I want a way to do this faster.
For example I found this:
String temp = TextView.getText().toString();
temp.substring(0,temp.lastIndexOf("\n"));
But I want to do it faster without copy data from Textview to a string value and dont using Sting.lastIndexOf (because its search in a string).
Can some one help me?
My Question isn't a dupplicate question becuase I want a way without using a string type!!!
I suggest overwriting the TextView class with your own implementation:
public class CustomTextView extends TextView{
// Overwrite any mandatory constructors and methods and just call super
public void removeLastLine(){
if(getText() == null) return;
String currentValue = getText().toString();
String newValue = currentValue.substring(0, currentValue.lastIndexOf("\n"));
setText(newValue);
}
}
Now you could use something along the lines of:
CustomTextView textView = ...
textView.removeLastLine();
Alternatively, since you seem to be looking for a one-liner without creating a String temp for some reason, you could do this:
textView.setText(textView.getText().toString().replaceFirst("(.*)\n[^\n]+$", "$1"));
Regex explanation:
(.*) # One or more character (as capture group 1)
\n # a new-line
[^\n] # followed by one or more non new-lines
$ # at the end of the String
$1 # Replace it with the capture group 1 substring
# (so the last new-line, and everything after it are removed)
Try it online.
Use the System.getProperty("line.seperator") instead of "\n"
public void removeLastLine(TextView textView) {
String temp = textView.getText().toString();
textView.setText(
temp.substring(0, temp.lastIndexOf(System.getProperty("line.seperator") )));
}
Try this:
public String removeLastParagraph(String s) {
int index = s.lastIndexOf("\n");
if (index < 0) {
return s;
}
else {
return s.substring(0, index);
}
}
and use it like:
tv.setText(removeLastParagraph(tv.getText().toString().trim());

How to validate an empty textField that can accepts only integers?

I wrote like this; but it fails to integer only textfields
if(textField_1.getText().length()==0)
JOptionPane.showMessageDialog(null, "enter text in textfield");
Please help...
Typically, when you are validating user input in Java, you will want to check for both null and empty string values. To check String objects for equality, you must use the .equals() method (not the == operator). Thus, a check for an empty String value might look something like this:
if ( val == null || val.trim().equals( "" ) )
{
// handle empty String case
}
else
{
// handle non-empty String case
}
Hope this helps
if(textField_1.getText().isEmpty()){
JOptionPane.showMessageDialog(null, "enter text in textfield");
}

Why does this Java code throw a NumberFormatException?

I'm playing around with a GUI Sudoku solver that uses an array of JTextFields (gridArray) for display and an int array (sudokuGrid) for the actual solving. When I run it and it tries to cast the JTextField strings to ints, it throws a NumberFormatException on parsing the strings into ints, specifically this message:
java.lang.NumberFormatException: For input string: ""
Here's the section of code that's causing me trouble:
// create solveButton
solveButton = new JButton("Solve It!");
solveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
// create grid and call Solve()
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
if (gridArray[i][j].getText() == "")
{sudokuGrid[i][j] = 0;}
else {sudokuGrid[i][j] = Integer.parseInt(gridArray[i][j].getText());}
}
} // end for loop
Solver(sudokuGrid);
// display solution
for(int i=0;i<9;i++) {
for(int j=0;j<9;j++) {
gridArray[i][j].setText(String.valueOf(sudokuGrid[i][j]));
}
} // end for loop
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(mainFrame,e.toString(),"Number Format Exception",JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(mainFrame,"Sorry, something broke, try again.","Solve Error",JOptionPane.ERROR_MESSAGE);
} // end try-catch
} // end actionPerformed()
}); // end solveButton ActionListener
I thought that the if-else would catch the empty fields and only try the parseInt if there was a value present, but if anyone can enlighten me I'd appreciate it.
Your problem is here:
if (gridArray[i][j].getText() == "")
You can't compare strings that way. Do it this way instead:
if (gridArray[i][j].getText().equals(""))
You are checking string equality using ==, which is only for reference equality. Perhaps you meant to write:
gridArray[i][j].getText().equals("")
Don't ask the TextArea for it's text, since this may be prone to be still in the editing process. Check the underlying document itself.
Document document = gridArray[i][j].getDocument();
sudokuGrid[i][j] = document.getLength() == 0 ? 0 : Integer.parseInt(document.getText(0, 1);
Also... why a JTextArea? Why not a JTextField? You might even combine this with a JSpinner with values from 0 (which is inerpreted as empty to 9.
Using == -comparison with strings does not mean checking for equality of the text (string contents), but instead equality of the String-objects (testing are they the exact same OBJECT). Use String.equals() instead.
The problem is your equality check:
gridArray[i][j].getText() == ""
This does not do what you're intending. In Java this checks whether the two strings are the same object not whether their values are equal.
You should use the String.equals() method to evaluate whether the text field is empty.

How to filter keys in MIDP TextField?

I have a TextField.PhoneNumber but I would like to filter out "+" character. In other words, I need a new constraint for TextField. Is there a way to define a new constraint with TextField?
How about preventing keys from cycling on a mobile phone within a midp?
It might not what you really want.
But, MIDP does not support change constraint rule as you want. So, I suggest HACK for your purpose.
How about use ItemStateListener to check if text field contains string which you want to filter out and if this string is exist, change text field forcefully.
The code could be looks like below:
// set item state listener
form.setItemStateListener(this);
// check if text field contains invalid string
// then replace it
public void itemStateChanged(Item item) {
if (item == getTextField()) {
TextField t = (TextField)item;
String s = t.getString();
// + is invalid string
int pos = s.indexOf("+");
if (pos != -1) {
t.setString(s.substring(0, pos) + s.substring(pos + 1));
}
}
}

Categories