string to int,causing app to stop - android

final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
total_wt=ed11.getText().toString();
int rec = Integer.parseInt(recy_wt);
int nrec = Integer.parseInt(nonrec_wt);
ed11.setText(String.valueOf(rec + nrec));
The input I am giving is,ed7=10kg and ed8=20kg,and it will be displayed in ed11
as 30kg,but the app is unfortunately stopping.
If I am not writing 'kg',it is correctly displaying the totalwt.
But I want to display 'kg' in the answer.

There is already a solution here (can't flag as duplicate)
Find and extract a number from a string
Extract the digit part from the string and then parse it to an integer

Try this out
String regexp = "/^[0-9]+kg$/g"; //It accepts only '<number><kg>' format
int weight = 0;
if (recy_wt.matches(regexp) && nonrec_wt.matches(regex)) {
//It's valid input
Scanner scan = new Scanner(recy_wt);
weight = Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
Scanner scan = new Scanner(nonrec_wt);
weight += Integer.parseInt(scan.findInLine("\\d+(\\.\\d+)?"));
}
ed11.setText(String.valueOf(weight + "Kg"));

If the only possible unit is kg, then try like this
final EditText ed7 = (EditText)findViewById(R.id.Recycleweight);
final EditText ed8 = (EditText)findViewById(R.id.Nonweight);
final EditText ed11 = (EditText)findViewById(R.id.totalweight);
int weight = 0;
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
recy_wt = recy_wt.replace("kg","");
nonrec_wt = nonrec_wt.replace("kg","");
weight += Integer.parseInt(recy_wt) + Integer.parseInt(nonrec_wt);
ed11.setText(weight + "kg");

This will work:-
recy_wt=ed7.getText().toString();
nonrec_wt=ed8.getText().toString();
String n=recy_wt.replace("kg","");
String n1=nonrec_wt.replace("kg","");
weight += Integer.parseInt(n) + Integer.parseInt(n1);
ed11.setText(weight + "kg");
storing the replaced one in a string and then converting to int will help.

Related

How to get split string with special characters in android?

I have a string named namely "-10.00","-100.00","-1000.00". I want to get value like "10","100","1000" from that string. I have tried to get substring but did not able to get.
code i have tried
String amount = "-10.00";
String trimwalletBalance = amount.substring(0, amount.indexOf('.'));
From above i only get "-10".
String trimwalletBalance = amount.substring(1, amoun.indexOf("."));
Its very simple.
Do it like String trimwalletBalance = amount.substring(1, amount.indexOf('.'));
Instead of position 0, You should get substring from position 1
Convert it into integer and then name it positive:
String amount = "-10.00";
int amountInt = (int) Double.parseDouble(amount);
if(amountInt<0)amountInt*=-1;
Try
String amount = "-10.00";
int value = (int) Double.parseDouble(amount);
if(value < 0) value *= -1;
//value will be 10
OR
String text = amount.substring(1, amount.indexOf('.'));

format a string with fill places

I have setup an edittext box and set the maxlength to 10. When I copy the edittext to a string myTitles. I need the myTiles to be 10 chars long and not dependent on what is entered in the edittext box.
myTitles[0] = TitlesEdit.getText().toString();
The edittext was filled with ABCD so I need to add 6 spaces or placeholders after the ABCD. I have seen other post with str_pad and substr without success
myTitles[0] = str_pad(strTest, 0, 10);
myTitles[0] = substr(strTest,0, 10);
Try something like
public static String newString(String str) {
for (int i = str.length(); i <= 10; i++)
str += "*";
return str;
}
This will return a String with * replaced for the empty ones.
So, for eg, if your String is abcde, then on calling newString() as below
myTitles[0] = newString("abcde");
will return abcde***** as the output.
String s = new String("abcde");
for(int i=s.length();i<10;i++){
s = s.concat("-");
}
Then output your string s.
Thank you Lal, I use " " to fill and it worked fine. here is my new code.
String strTest = TitlesEdit.getText().toString();
for (int i = strTest.length(); i <= 10; i++) {
strTest += " ";
}
Log.d("TAG", "String" + strTest);
myTitles[intLinenumber] = strTest;

Getting OutOfBoundsException while pagination a String

I am creating an epub reader for android. For the pagination part, I am trying to get the whole string content and then search for space in the string. Then I get the text height and compare it with the screen height. if still (text height < screen height) I loop through the string and do the same thing in a while loop.
Every thing went well, but when it comes to the end of the string I get IndexOutOfBoundsException. I have attached the screenshot of the Logcat below.
The code I used to get the no of pages is like this
public String getNoOfPages(String text){
String remainingString = "";
try{
int screenHeight = getScreenHeight();
String originalText = text;
String strToModify = text;
StringBuilder newString = new StringBuilder();
StringBuilder oldString = new StringBuilder();
int startIndex = 0;
String strToFind = " ";
int index = strToModify.indexOf(strToFind,startIndex);
newString.append(originalText.substring(startIndex, index+1));
oldString.append(newString.toString());
startIndex = index+1;
int textHeight = getTextHeight(newString.toString());
while(textHeight < screenHeight){
index = strToModify.indexOf(strToFind,startIndex);
oldString.replace(0,oldString.toString().length(),newString.toString());
newString.append(originalText.substring(startIndex, index+1));
startIndex = index+1;
textHeight = getTextHeight(newString.toString());
}
remainingString = originalText.substring(oldString.length()-1,originalText.length());
}catch(Exception e){
Log.d("chathura123","Error in getNoOfPages " );
e.printStackTrace();
}
return remainingString;
}
The logic is when the remaining string is an empty string("") ,it means that is the end of the content of the page. So I want to check until it returns an empty string.
The above method is called inside another while loop. (In Async Task)
String tmp = null;
try{
tmp = reader.getNoOfPages(content);
while (!tmp.equals("")) {
tmp = reader.getNoOfPages(tmp);
page_count++;
if(page_count==80){
Log.d("chathura123", "80 th iteration");
}
Log.d("chathura123", "inside while "+page_count);
}
}catch(Exception e){
Log.d("chathura123", "error occured in getPageCount");
}
What is the wrong with this? Why I am getting OutOfBoundsException?
Thank you.
may be on the last line, when there are no characters there is an error for originalText.substring(startIndex, index+1) what if originalText doesnt have index+1 length/index.

Show source code in TextView correctly indented and parsed

Is it possible to parse HTML code in a verbatim mode or something similar so that the source code fragments that eventually may appear (enclosed between pre and code HTML tags) can be displayed properly?
What I want to do is show source code in a user-friendly mode (easy to distinguish from the rest of the text, keep indentation, etc.), as Stack Overflow does :)
It seems that Html.fromHtml() supports only a reduced subset of HTML tags.
TextView will never succeed supporting all the html formating and styling you would want it to. Use WebView instead.
TextView is native and more lightweight, but exactly because of its lightweightedness it will not understand some of the directives you describe.
Finally I preparsed by myself the HTML code received, since Html.fromHtml does not support the pre and code tags, y replaced them with my custom format and pre-parsed the code inside those tags replacing "\n" with <br/> and " " with .
Then I send the results to Html.fromHtml, and the result is just fine:
public class HtmlParser {
public static Spanned parse(String text) {
if (text == null) return null;
text = parseSourceCode(text);
Spanned textSpanned = Html.fromHtml(text);
return textSpanned;
}
private static String parseSourceCode(String text) {
if (text.indexOf(ORIGINAL_PATTERN_BEGIN) < 0) return text;
StringBuilder result = new StringBuilder();
int begin;
int end;
int beginIndexToProcess = 0;
while (text.indexOf(ORIGINAL_PATTERN_BEGIN) >= 0) {
begin = text.indexOf(ORIGINAL_PATTERN_BEGIN);
end = text.indexOf(ORIGINAL_PATTERN_END);
String code = parseCodeSegment(text, begin, end);
result.append(text.substring(beginIndexToProcess, begin));
result.append(PARSED_PATTERN_BEGIN);
result.append(code);
result.append(PARSED_PATTERN_END);
//replace in the original text to find the next appearance
text = text.replaceFirst(ORIGINAL_PATTERN_BEGIN, PARSED_PATTERN_BEGIN);
text = text.replaceFirst(ORIGINAL_PATTERN_END, PARSED_PATTERN_END);
//update the string index to process
beginIndexToProcess = text.lastIndexOf(PARSED_PATTERN_END) + PARSED_PATTERN_END.length();
}
//add the rest of the string
result.append(text.substring(beginIndexToProcess, text.length()));
return result.toString();
}
private static String parseCodeSegment(String text, int begin, int end) {
String code = text.substring(begin + ORIGINAL_PATTERN_BEGIN.length(), end);
code = code.replace(" ", " ");
code = code.replace("\n","<br/>");
return code;
}
private static final String ORIGINAL_PATTERN_BEGIN = "<pre><code>";
private static final String ORIGINAL_PATTERN_END = "</code></pre>";
private static final String PARSED_PATTERN_BEGIN = "<font color=\"#888888\"><tt>";
private static final String PARSED_PATTERN_END = "</tt></font>";
}

Android basic math in textview

I am trying to add two numbers and display them in the textview using this code. The problem here is that it doesn't add the numbers, it just displays the entire string.
CharSequence fnum, snum, symbol;
final TextView CalTextBox = (TextView) findViewById(R.id.MainTextview);
symbol = "+"; // addition selected
fnum = CalTextBox.getText(); // store number into fnum
snum = CalTextBox.getText(); //new number will be added in the code and be stored into snum
CalTextBox.setText(""); // delete whats in the text box
CalTextBox.setText(snum + "" + symbol + "" + fnum); // add two numbers
Well, the '+' operator performs concatenation if used on strings (like in this case). To perform a math operation, you have to convert them to numbers first. I think you can use this:
// Convert the 2 String to integer values
int first = Integer.valueOf(fnum);
int second = Integer.valueOf(snum);
// Compute the sum
int sum = first + second;
// Create the String you can use to display in the TextView
String textToDisplay = String.valueOf(sum);
snum = "2";
fnum = "3";
symbol = "+";
snum + "" + symbol + "" + fnum = "2+3"
Instead you should convert String into integer or double and make appropriate controls such as null or empty, or non-numeric then,
int result = Integer.parseInt(snum) + Integer.parseInt(fnum);
CalTextBox.setText("" + result);
For mathematical operations is best to use int, long or double variable types. Instead of CharSequence use for example int.
to get integer (int) from String (text) use:
int fnum, snum, symbol;
int fnum = Integer.parseInt("10"); or
fnum = Integer.parseInt(CalTextBox.getText());
CalTextBox.setText("" + (snum + symbol + fnum));

Categories

Resources