Trying to clear one character from TextView - android

I made a calculator app and I made a clear Button that clears the TextView.
private TextView _screen;
private String display = "";
private void clear() {
display = "";
currentOperator = "";
result = "";
}
I got this code from Tutorial and set the clear button onClick to onClickClear, so it do that part of the code and it works. Now I have made this code delete only one number at a time and it don't work. What can be done to delete only one number at a time?
public void onClickdel(View v) {
display = "";
}

Below code will delete one char from textView.
String display = textView.getText().toString();
if(!TextUtils.isEmpty(display)) {
display = display.substring(0, display.length() - 1);
textView.setText(display);
}

You are modifying the string and not the textview.
To clear the TextView use:
_screen.setText("");
To remove the last character:
String str = _screen.getText().toString();
if(!str.equals(""))
str = str.substring(0, str.length() - 1);
_screen.setText(str);

String display = textView.getText().toString();
if(!display.isEmpty()) {
textView.setText(display.substring(0, display.length() - 1));
}

Related

How to delete the last occurrence of a function name (e.g. "cos" or "ln" or "tan") in a calculator edittext with one click?

I wanted to delete the last occurrence of a function name in a calculator edittext with one click.
I already have a delete button, which looks like this:
private void onDelete() {
final Editable formulaText = mFormulaEditText.getEditableText();
final int formulaLength = formulaText.length();
if (formulaLength > 0) {
formulaText.delete(formulaLength - 1, formulaLength);
}
}
I tried to get the last 3 character than if it equals with the function name, delete 3 letters, but the problem is that there are some longer (e.g.: atanh) or shorter function names (e.g.: ln).
P. S. Sorry for my English.
You could use a regular expression:
private static String removeLastMathFunction(String input) {
final String mathFnRegex = "(ln|log|a?(sin|cos|tan)h?)";
final String lastMathFnRegex = mathFnRegex + "(?!.*" + mathFnRegex + ")";
return input.replaceAll(lastMathFnRegex, "");
}
private void onDelete() {
String oldInputValue = mFormulaEditText.getText().toString();
String newInputValue = removeLastMathFunction(oldInputValue);
mFormulaEditText.setText(newInputValue);
}

ReplaceAll not working

I'm using google volley to retrieve source code from website. Some looping was done to capture the value in the code. I've successfully captured the data I wanted, but error was shown: NumberFormatException: Invalid float: "2,459.00"
My intention was to store the value after the class=ListPrice>
Sample:
RM 2,899.00
The example value of the source code I wanted to save is "RM2,459.00 "
Below is the code I've written:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lazada_result);
lelongResult = (TextView) findViewById(R.id.lelong_result);
RequestQueue lelong = MyVolley.getRequestQueue(this);
StringRequest myLel = new StringRequest(
Method.GET,
"http://list.lelong.com.my/Auc/List/List.asp?DA=A&TheKeyword=iphone&x=0&y=0&CategoryID=&PriceLBound=&PriceUBound=",
RetrieveLelong(), createMyReqErrorListener());
lelong.add(myLel);
}
private Response.Listener<String> RetrieveLelong() {
return new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ArrayList<Float> integers = new ArrayList<>();
String to = "class=ListPrice>";
String remainingText = response;
String showP = "";
while (remainingText.indexOf(to) >= 0) {
String tokenString = remainingText.substring(remainingText
.indexOf(to) + to.length());
String priceString = tokenString.substring(0,
tokenString.indexOf("<"));
float price = Float.parseFloat(priceString.replaceAll("[^\\d,]+", "").trim());
integers.add((price / 100));
remainingText = tokenString;
}
for (int i = 0; i < integers.size(); i++) {
String test1 = Float.toString(integers.get(i));
showP += test1 + "\n";
}
lelongResult.setText(showP);
}
};
}
The problem was as below:
I've tried all sort of replaceAll(),
1)replaceAll("[^\d,]+","") result:2,89900
replace all character except digits and comma works.
2)replaceAll("[^\d]+","") result:Invalid int""
replace all character include comma and dot ,not working
3)replaceAll("[^\d.]+,"") result:Invalid int""
replace all character exclude digits and dot, not working
From the experiment 2&3 coding above,I've noticed that if the comma were removed,i cant parseFloat as the value received by it is: "".NumberFormatException:Invalid Float:"" shown.
From the experiment 1,NumberFormatException:Invalid Float "2,45900" is showned.
The problem was replacing comma ,the code will not work but with the presence of comma ,the value cannot be stored into string
try this:
float price = Float.parseFloat(priceString.replaceAll("RM", "").trim());
use `replaceAll(Pattern.quote(","), "");
EDIT
if you want only numbers then use this
String s1= s.replaceAll("\D+","");
Try to parse the number by specifying the Locale.
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();
I'm just guessing the locale, don't know what you should use, depends on country
You need to do it one by one
priceString=priceString.replaceAll("\\D", "");
priceString=priceString.replaceAll("\\s", "");
now
priceString=priceString.trim();
float price = Float.parseFloat(priceString);
the problem is that in your code:
priceString.replaceAll(Pattern.quote(","), "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
You are replacing coma but not storing the value!
you have to do:
priceString = priceString.replaceAll(",", "");
float price = Float.parseFloat(priceString.replaceAll("\\D+\\s+", "").trim());
I'm not sure of the pattern "\D+\s" because if you remove the coma you don't need to replace anything else (except "RM" that i assume you already removed)
Update: set locale and parse a number:
NumberFormat format = NumberFormat.getInstance(Locale.KOREAN);
Number number = format.parse(priceString.replaceAll("RM", ""));
double d = number.doubleValue();

How get the first letter of TextView in Android?

I have not found documentation on how I can get the first letter of a value in a TextView?
Very easy,
String strTextview = textView.getText().toString();
strTextView = strTextView.substring(0,1);
Alternatively you can try following way too
char firstCharacter = textView.getText().toString().charAt(0);
To get the first letter you'll have to make this call:
char firstCharacter = myTextView.getText().charAt(0);
Use the method from below. Provide the string from TextView as the parameter.
public String firstStringer(String s) {
String str= s.substring(0, Math.min(s.length(), 1));
return str;
}
You can use this
TextView tv = (TextView) findViewById(R.id.textview);
String frstLetter = tv.getText().substring(0, 1);
it is simple. To retrieve the Text from the TextView you have to use getText().toString();
String textViewContent = textViewInstance.getText().toString();
and the first letter textViewContent.charAt(0)
To fetch the content of the string from TextView:
String content = textView.getText().toString();
To fetch the first character
char first = content.charAt(0);
Try this
String value = text.getText().toString();
String firstTen = value.substring(0, 1);

Don't change varriable value after first call

I'm new android/java programmer and I can't find anywhere how to set default varriable value only on first call. My console log delete after second call. My code looks like:
public class Ftp {
[...]
//Console
String console_strings[] = new String [15];
int console_line = 0;
//
[...]
public void drawConsole(String msg){
CharSequence time = DateFormat.format("hh:mm:ss", d.getTime());
String message = "["+time+"] "+msg;
TextView console = (TextView)((Activity)context).findViewById(R.id.console);
String newString = "";
for(int i = 0; i < console_strings.length; i++){
if(console_strings[i] != null)
newString += console_strings[i] + "\n";
else
{
console_strings[i] = message;
newString += console_strings[i] + "\n";
break;
}
}
console.setText(newString);
}
}
Whenever I want to add something to the console, it delete old text value.
There are multiple ways to do this. The problem you are having is that you are setting the entire textview's text at once. You could do one of a few things. You could do
console.setText(console.getText() + newString);
or
console.append(newString);
Both of these would work. There are multiple other ways, but those should do it for you.
TextView has also an append method

How to delete the old lines of a TextView

I'm developping an app which constantly needs to show the results to the user in a TextView like some sort of log.
The app works nicely and it shows the results in the TextView but as long as it keeps running and adding lines the app gets slower and crashes because of the character length of the TextView.
I would like to know if the android API provides any way to force a TexView to automatically delete the oldest lines that were introduced in order to make room for the new ones.
I had the same problem. I just resolved it.
The trick is to use the getEditableText() method of TextView. It has a replace() method, even a delete() one. As you append lines in it, the TextView is already marked as "editable", which is needed to use getEditableText(). I have something like that:
private final static int MAX_LINE = 50;
private TextView _debugTextView; // Of course, must be filled with your TextView
public void writeTerminal(String data) {
_debugTextView.append(data);
// Erase excessive lines
int excessLineNumber = _debugTextView.getLineCount() - MAX_LINE;
if (excessLineNumber > 0) {
int eolIndex = -1;
CharSequence charSequence = _debugTextView.getText();
for(int i=0; i<excessLineNumber; i++) {
do {
eolIndex++;
} while(eolIndex < charSequence.length() && charSequence.charAt(eolIndex) != '\n');
}
if (eolIndex < charSequence.length()) {
_debugTextView.getEditableText().delete(0, eolIndex+1);
}
else {
_debugTextView.setText("");
}
}
}
The thing is, TextView.getLineCount() returns the number of wrapped lines, and not the number of "\n" in the text... It is why I clear the whole text if I reach the end of the text while seeking the lines to delete.
You can do that differently by erasing a number of characters instead of erasing a number of lines.
This solution keeps track of the log lines in a list and overwrites the textview with the contents of the list on each change.
private List<String> errorLog = new ArrayList<String>();
private static final int MAX_ERROR_LINES = 70;
private TextView logTextView;
public void addToLog(String str) {
if (str.length() > 0) {
errorLog.add( str) ;
}
// remove the first line if log is too large
if (errorLog.size() >= MAX_ERROR_LINES) {
errorLog.remove(0);
}
updateLog();
}
private void updateLog() {
String log = "";
for (String str : errorLog) {
log += str + "\n";
}
logTextView.setText(log);
}
Here is an example that adds lines to an output log limited by the set max lines. The scrollview will auto scroll to the bottom after every line is added. This example work purely with the contents of the TextView so it doesn't have the need for a separate data collection.
Add the following to your activity xml:
<ScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" >
<TextView
android:id="#+id/textViewOutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1000" />
</ScrollView>
In your activity add the following code:
private static final int MAX_OUTPUT_LINES = 50;
private static final boolean AUTO_SCROLL_BOTTOM = true;
private TextView _textViewOutput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_textViewOutput = (TextView) findViewById(R.id.textViewOutput);
}
//call to add line(s) to TextView
//This should work if either lineText contains multiple
//linefeeds or none at all
private void addLinesToTextView(String lineText) {
_textViewOutput.append(lineText);
removeLinesFromTextView();
if(AUTO_SCROLL_BOTTOM)
_scrollView.post(new Runnable() {
#Override
public void run() {
_scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
// remove leading lines from beginning of the output view
private void removeLinesFromTextView() {
int linesToRemove = _textViewOutput.getLineCount() - MAX_OUTPUT_LINES;
if (linesToRemove > 0) {
for (int i = 0; i < linesToRemove; i++) {
Editable text = _textViewOutput.getEditableText();
int lineStart = _textViewOutput.getLayout().getLineStart(0);
int lineEnd = _textViewOutput.getLayout().getLineEnd(0);
text.delete(lineStart, lineEnd);
}
}
}
The TextView shows what you set via setText() method. So this sounds to me like you should cut down the input you provide.
To empty the TextView, you can do setText("");
Kotlin answer of Vincent Hiribarren
fun write_terminal_with_limit(data: String?, limit:Int)
{
log_textView.append(data)
val nb_line_to_del: Int = log_textView.lineCount - limit
// Erase excessive lines
if (nb_line_to_del > 0)
{
var end_of_line_idx = -1
val char_seq: CharSequence = log_textView.text
for (i in 0 until nb_line_to_del)
{
do
{
end_of_line_idx++
}
while (end_of_line_idx < char_seq.length && char_seq[end_of_line_idx] != '\n')
}
if (end_of_line_idx < char_seq.length)
{
log_textView.editableText.delete(0, end_of_line_idx + 1)
}
else
{
log_textView.text = ""
}
}
}
I made personnal adjustment...
I think you are using TextView.append(string) then it will add to old text.
If you are setting using setText it will replace the old text
This is an old one, but I just found looking for a solution to my own problem.
I was able to remove all TextViews from a LinearLayout using nameoflayout.removeAllViews();
There is another method that will allow you to remove views from specified places in the layout using ints, it's: nameoflayout.removeViews(start, count); so I'm sure you could create a time out for how long textviews remain visible.
No, android API doesn't provide any functionally that delete oldest lines from textview automatically till API level 25. you need to do it logically.
Try to write a function that takes an old string on TextView and add new string to it, then get substring last strings that TextView capable. And set it to TextView. Something like this:
String str = textview.getText();
str += newstring;
int ln = str.length();
ln = ln-250;
if (ln<0) ln=0;
str = str.substring(ln);
textview.setText(str);
reference Vincent Hiribarren answer.
make it simple-->
TextView _debugTextView;
//if excess 20 lines keep new 200 chars
if(_debugTextView.getLineCount() >20) _debugTextView.getEditableText().delete(0,_debugTextView.getText().length()-200);

Categories

Resources