Hide part of a string in EditText (Java/Android) - java

Is it possible to hide part of a string in the editText with a method like
editText.hide(int start, int finish);
so that in the display I can't read the hidden part of the string, but if I use a method like editText.getText() in the code, it will include the hidden string?

You can do something like:
String wholeString = editText.getText().toString();
editText.setText(editText.getText().toString().substring(int start, int end));
where start and end are integers that you want your string to begin and end at the positions you set.
So now you have the whole string before it was hidden. Additionally, if you want to hide a certain part in the middle of your editText, you can do something like this:
editText.setText(editText.getText().toString().substring(0, 20) + editText.getText().toString().substring(25, 30));
where you set your editText text with many strings. This will hide the string from position 21 till 25. You have to modify it according to your needs.
You may also need to know a method for a string called lastIndexOf("Some Text")
Example:
//You have a string called example.
String example = "Android development is fun and nice."
String cutExample = example.substring(example.lastIndexOf("is") +3, example.lastIndexOf(".");
The result will be: "fun and nice".
So lastIndexOf() will return the position of the defined string.
Test with what I wrote. Hope that helps.

Related

I want to print a Forward Slash, but i am getting a warning , how to solve [duplicate]

I am setting text using setText() by following way.
prodNameView.setText("" + name);
prodOriginalPriceView.setText("" + String.format(getString(R.string.string_product_rate_with_ruppe_sign), "" + new BigDecimal(price).setScale(2, RoundingMode.UP)));
In that First one is simple use and Second one is setting text with formatting text.
Android Studio is so much interesting, I used Menu Analyze -> Code Cleanup and i got suggestion on above two lines like.
Do not concatenate text displayed with setText. Use resource string
with placeholders. less... (Ctrl+F1)
When calling TextView#setText:
Never call Number#toString() to format numbers; it will not handle fraction separators and locale-specific digits properly. Consider
using String#format with proper format specifications (%d or %f)
instead.
Do not pass a string literal (e.g. "Hello") to display text. Hardcoded text can not be properly translated to other languages.
Consider using Android resource strings instead.
Do not build messages by concatenating text chunks. Such messages can not be properly translated.
What I can do for this? Anyone can help explain what the thing is and what should I do?
Resource has the get overloaded version of getString which takes a varargs of type Object: getString(int, java.lang.Object...). If you setup correctly your string in strings.xml, with the correct place holders, you can use this version to retrieve the formatted version of your final String. E.g.
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
using getString(R.string.welcome_message, "Test", 0);
android will return a String with
"Hello Test! you have 0 new messages"
About setText("" + name);
Your first Example, prodNameView.setText("" + name); doesn't make any sense to me. The TextView is able to handle null values. If name is null, no text will be drawn.
Don't get confused with %1$s and %2$d in the accepted answer.Here is a few extra information.
The format specifiers can be of the following syntax:
%[argument_index$]format_specifier
The optional argument_index is specified as a number ending with a “$” after the “%” and selects the specified argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.
The required format specifier is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.
Example
We will create the following formatted string where the gray parts are inserted programmatically.
Hello Test! you have 0 new messages
Your string resource:
< string name="welcome_messages">Hello, %1$s! You have %2$d new
messages< /string >
Do the string substitution as given below:
getString(R.string.welcome_message, "Test", 0);
Note:
%1$s will be substituted by the string "Test"
%2$d will be substituted by the string "0"
I ran into the same lint error message and solved it this way.
Initially my code was:
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + quantity);
}
I got the following error
Do not concatenate text displayed with setText. Use resource string with placeholders.
So, I added this to strings.xml
<string name="blank">%d</string>
Which is my initial "" + a placeholder for my number(quantity).
Note: My quantity variable was previously defined and is what I wanted to append to the string. My code as a result was
private void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText(getString(R.string.blank, quantity));
}
After this, my error went away. The behavior in the app did not change and my quantity continued to display as I wanted it to now without a lint error.
Do not concatenate text inside your setText() method, Concatenate what ever you want in a String and put that String value inside your setText() method.
ex: correct way
int min = 120;
int sec = 200;
int hrs = 2;
String minutes = String.format("%02d", mins);
String seconds = String.format("%02d", secs);
String newTime = hrs+":"+minutes+":"+seconds;
text.setText(minutes);
Do not concatenate inside setText() like
text.setText(hrs+":"+String.format("%02d", mins)+":"+String.format("%02d", secs));
You should check this thread and use a placeholder like his one (not tested)
<string name="string_product_rate_with_ruppe_sign">Price : %1$d</string>
String text = String.format(getString(R.string.string_product_rate_with_ruppe_sign),new BigDecimal(price).setScale(2, RoundingMode.UP));
prodOriginalPriceView.setText(text);
Don't Mad, It's too Simple.
String firstname = firstname.getText().toString();
String result = "hi "+ firstname +" Welcome Here";
mytextview.setText(result);
the problem is because you are appending "" at the beginning of every string.
lint will scan arguments being passed to setText and will generate warnings, in your case following warning is relevant:
Do not build messages by
concatenating text chunks. Such messages can not be properly
translated.
as you are concatenating every string with "".
remove this concatenation as the arguments you are passing are already text. Also, you can use .toString() if at all required anywhere else instead of concatenating your string with ""
I fixed it by using String.format
befor :
textViewAddress.setText("Address"+address+"\n"+"nCountry"+"\n"+"City"+"city"+"\n"+"State"+"state")
after :
textViewAddress.setText(
String.format("Address:%s\nCountry:%s\nCity:%s\nState:%s", address, country, city, state));
You can use this , it works for me
title.setText(MessageFormat.format("{0} {1}", itemList.get(position).getOppName(), itemList.get(position).getBatchNum()));
If you don't need to support i18n, you can disable this lint check in Android Studio
File -> Settings -> Editor -> Inspections -> Android -> Lint -> TextView Internationalization(uncheck this)
prodNameView.setText("" + name); //this produce lint error
val nameStr="" + name;//workaround for quick warning fix require rebuild
prodNameView.setText(nameStr);
I know I am super late for answering this but I think you can store the data in a varible first then you can provide the variable name. eg:-
// Java syntax
String a = ("" + name);
String b = "" + String.format(getString(R.string.string_product_rate_with_ruppe_sign);
String c = "" + new BigDecimal(price).setScale(2, RoundingMode.UP));
prodNameView.setText(a);
prodOriginalPriceView.setText(b, c);
if it is textView you can use like that : myTextView.text = ("Hello World")
in editText you can use myTextView.setText("Hello World")

How to get the current Letter at cursor position toString in java?

I want to get the current letter in EdiText to String, I tried using some ways but without success, because I'm beginner and still learning.
what I want exactly is to insert special char after every written special char (in onTextChanged event), after get it into String to use (if ...equals ...)
String selected = edittext1.getText().toString().substring(startSelection);
Editable editAble = edittext1.getEditableText();
int start = edittext1.getSelectionStart();
if (selected.equals("(")) {
editAble.insert(start, ")");
}
this code not working.
any suggestions ?

Is there a way to automatically select text in TextView?

Is there a way to automatically select or highlight a predetermined area of text on TextView? For instance, I want a specific line on the TextView to be already pre-selected when I start the activity, instead of having the user select that area of text themselves.
What you're looking for is most likely the setSelection, function.
it works like this:
EditText edText = findViewById(id);
edText.setSelection(start, stop);
The setSelection() function takes 2 arguments start and stop, both are ints, its the index of the character where you want the selection to start and the index of the character where you want the selection to end.
for example setSelection(0,1) will select the first character of the EditText.
If you want to select a specific String in an EditText you could do something like:
EditText edText = findViewById(id);
String lookingFor = "whatever youre looking for";
//You get the index of the first character of the string you're looking for
int start = edText.getText().toString().indexOf(lookingFor);
//You add the string's length to the index so the selection actually selects the
//whole string.
int stop = start+lookingFor.length();
//You -start- selecting from the 1st character and -stop- at the last character
//Of the string you're looking for.
edText.setSelection(start,stop);

How to format Java Strings in the Java class not using the xml

I have a String array list set up to populate text to multiple intro screens. As the text is populated in the actualy Java class and not in the xml resource file I want to know how can I make certain words in the text bold from within the java class?
public String [] slide_descriptions = {
"I want this text in bold \n",
"and maybe this too!"
};
You can use Html tags. For example:
textView.setText(Html.fromHtml("< b >This is Bold< /b >"));
For String, do it like this:
public String [] slide_descriptions = {
"<b>I want this text in bold</b> \n",
"<b>and maybe this too!</b>"
};
So at the end when you put the string in the textview:
textView.setText(Html.fromHtml(slide_description));
See answer below: link
However in comment says that This will slow down performance.
You can use spannable string as it is easy and less costly
SpannableString spannableString = new SpannableString(yourstringhere);
spannableString.setSpan(new StyleSpan(Typeface.BOLD),indexStart,indexEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

how to replace a word with in contains() Method form a JtextPane

Well, I'm trying to replace a word by using contains() Method:
String z = tfB.getText().toString();
String show = textPane.getText().toString();
if(show.contains(z)){
// how I specify the word that were found and change it without
effecting anything with in that line
}
well what I main by that:
What I'm trying to do is get the value from the user.
then search if it found replace it with something. For example:
String x = "one two three four five";
It should set the textPane to "one two 3 four five"
or
"one two 3-three-3 four five"
could any one please tell me how to do it.
Thank you
What I'm trying to do is get the value from the user. then search if it found replace it with something.
Don't use the contains() method because you will need to search the text twice:
once to see if the text is found in the string
again to replace the text with a new string.
Instead, use the String.indexof(...) method. It will return the index of the text IF it is found in the String.
Then you should replace the text directly in the Document of the text pane, not in the String itself. So the code would be something like:
int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
String search = "abc...";
int offset = text.indexOf(search);
if (offset != -1)
{
textPane.setSelectionStart(offset);
textPane.setSelectionEnd(offset + search.length();
textPane.replaceSelection("123...");
}
Also, not that you get the text from the Document, not the text pane. This is to make sure the offsets are correct when you replace the text in the Document. Check out Text and New Lines for more information on why this is important.

Categories