TextView Does Not Return Anything Android - parsing

I have a function in Android wherein it gets the value returned by a TextView which are
totalcost_venue, totalcost_apparel, totalcost_souvenir, and totalcost_caterer.
The value is converted to double and after which I have to add those values. But I encountered an error when a particular TextView does not return any value. Any help will do. Thanks!
double totalcost_venue_finalconverted = Double.parseDouble(totalcost_venue.getText().toString());
double totalcost_apparel_finalconverted = Double.parseDouble(totalcost_apparel.getText().toString());
double totalcost_caterer_finalconverted = Double.parseDouble(totalcost_caterer.getText().toString());
double totalcost_souvenir_finalconverted = Double.parseDouble(totalcost_souvenir.getText().toString());
double total = (totalcost_venue_finalconverted + totalcost_apparel_finalconverted + totalcost_caterer_finalconverted +totalcost_souvenir_finalconverted);
String total_all= Double.toString(total);
totalcost_all.setText(total_all);
String totalcost_final = totalcost_all.getText().toString();
double budget_converted = Double.parseDouble(budget_event);
double totalcost_converted = Double.parseDouble(totalcost_final);
if(budget_converted <= totalcost_converted){
registerErrorMsg.setText(" Oops!! Already exceeded");

Double.parseDouble() may be throwing an exception if it recieves a null value, or it is recieves text.
To solve your issue with a null value, you could add the following check:
double totalcost_venue_finalconverted = 0;
if(!totalcost_venue.getText().toString().equals("")){
totalcost_venue_finalconverted = Double.parseDouble(totalcost_venue.getText().toString());
}

Related

The operator '[]=' isn't defined for the type 'String'

I'm getting an error in this code:
void main() {
List<String> wave(String str) {
List<String> results = [];
String newStr;
int i = 0;
for (String ltr in str.split('')) {
newStr = str;
if (ltr != ' ') {
newStr[i] = ltr.toUpperCase();
results.add(newStr);
}
i++;
}
return results;
}
print(wave(' gap '));
}
the error is at the line:
newStr[i] = ltr.toUpperCase;
Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!
In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.
To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:
if (ltr != ' ' && i < newStr.length) {
newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
results.add(newStr);
}
To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.
try to replace
newStr[i] = ltr.toUpperCase();
to
newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);
So the result will be [ Gap , gAp , gaP ]
Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

Why am I getting error as function call returns immutable value in swiftui?

I want to play songs from albums between some time gaps and I used this code to achieve that concept. but I don't know why I'm getting this error. please help me to fix it.
mysongsplayer.play()
let date = Date()
let calendar = Calendar.current
let now = calendar.component(.second, from: date)
let starting_song = Double(now) + mysongsplayer.duration + (myModel.delay * 60)
let stop_song = starting_song + (myModel.time * 60)
while (start_song > stop_song) {
for item in 0..<(selected_songs).count {
if (stop_song > starting_song) {
DispatchQueue.main.asyncAfter(deadline: .now() + starting_song) {
selected_songs[item].play()
Int(starting_song) += item + myModel.gap
}
}
}
}
so at this point I'm getting this error
Int(starting_song) += item + myModel.gap
Left side of mutating operator isn't mutable: function call returns immutable value
Issue 1: Thats because you when you type cast a value in swift, it returns an immutable value (read only). So statement Int(starting_song) will return a read only value, hence you can not change the value of it by adding item and myModel.gap.
Issue 2: Also you have declared starting_song as let so you cant change its value anyway.
First thing first, change let starting_song to var starting_song.
Next change Int(starting_song) += item + myModel.gap to
starting_song += Double(item + myModel.gap)
This will work because 1. You are casting the sum of item and gap to double and the starting_song is already a double (type check will not fail) 2. The type casted value (sum of item and gap) is not modified.
I would expect that you need to reverse the cast to Int.
starting_song += Int(item + myModel.gap)

Passing substring value of gridview to textbox

Please suggest me any idea to pass sub string value of grid view in text box.
frm.txtcustcode.text = dg.cells["custcode"].value.ToString().Trim();
I need to pass (0000001234) "01234" to txtcustcode.Text;
Below code might work fine:
frm.txtcustcode.Text= dg.Cells["CustomerCode"].Value.ToString().Trim().Substring(5,5);
I hope I understand your question correctly.
The code :
dg.cells["custcode"].value.ToString().Trim();
is a value in a grid and the value you get by using the code is : 0000001234
You would like to display this value in a textbox on the form as a value : 01234
If this is the case you could do the following:
//If the value of custcode always starts with 0's but wont contain 0's in the number.
String sCustCode = "0000001234";
sCustCode = sCustCode.Replace("0", "");
sCustCode = "0" + sCustCode;
MessageBox.Show(sCustCode); //Displays 01234
//Or if your CustCode can contain a 0 and always starts with 0's.
sCustCode = "0000001234";
int num = Int32.Parse(sCustCode); //Depending on the number format use the correct cast.
sCustCode = "0" + num.ToString();
MessageBox.Show(sCustCode); //Displays 01234
//Or you dont want to use a Cast to get your code in the fear of dataloss for some reason.
sCustCode = "0000001234";
int index = 0;
int position = 0;
foreach(char myChar in sCustCode)
{
if (myChar != '0')
{
position = index;
break;
}
index++;
}
if (position == 0)
{
//No starting 0 found
}
else
{
sCustCode = sCustCode.Substring(position - 1, sCustCode.Length - position +1);
}
MessageBox.Show(sCustCode); //Displays 01234
I am sure there are better ways of doing this, it depends on the purpose.
Hope this can help you in the correct direction.

Multiply UITextfields values with Double in Swift?

I am trying to Multiply
self.tipLable.text = String("\((enterBillAmountTextField.text! as NSString).integerValue * (middleTextField.text! as NSString).integerValue * (0.01))")
But getting error Binary operator * cannot be applied to operands of type Int and Double
I am taking values form UITextfields. How to do this multiplication?
extension Double {
// Convert Double to currency
var currency: String {
let formatter = NSNumberFormatter()
formatter.numberStyle = .DecimalStyle
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
return formatter.stringFromNumber(self) ?? "0"
}
}
tipLable.text = [enterBillAmountTextField, middleTextField].reduce(0.01) { $0 * (Double($1.text!) ?? 0) }.currency
A slightly shorter and clearer solution. Added a "currency" extension so it can still be done in one line :).
This works
self.tipLable.text = String("\( Double((enterBillAmountTextField.text! as NSString).integerValue) * Double((middleTextField.text! as NSString).integerValue) * 0.01)")
Swift doesn't know how to multiply an Int and a Double. Should the result be an Int or a Double?
Swift won't do implicit type conversion between different operands.
If you want your result to be a Double, both operands should be a Double. Then convert the Double to a String.
While this can all be concisely expressed in one single very long line, perhaps it's more readable and maintainable if you break it out into separate lines:
let subTotal = Double(billAmountTextField.text!) ?? 0
let percent = (Double(middleTextField.text!) ?? 0) * 0.01
let tip = subTotal * percent
self.tipLable.text = String(format: "%.2f", tip) // Handle rounding
The answer you gave is going to bring nightmare to you in some moment.
Try to keep yourself doing things in a way you can guarantee that you are going to be able to test it and that you/or others are going to be able to understand what you are doing there.
/**
Use this function to calculate tip, useful for later testing
- returns: Double Value of the tip you should give
*/
func calculateTip(billAmount billAmount:Double, middleValue:Double) -> Double {
/// Actually calculate Tip if everything is OK
return billAmount * middleValue * 0.01
}
Then in your #IBAction make sure you have correct data before asking
your function for a tip
/// If you have bill data, obtain Double value stored there,
/// if something fails, you should return nil
guard let billAmountText = enterBillAmountTextField.text, billAmount = Double(billAmountText) else {
return
}
/// If you have middle value data, obtain Double value stored there,
/// if something fails, you should return nil
guard let middleText = middleTextField.text, middleValue = Double(middleText) else {
return
}
Then you can call that function
let tip = calculateTip(billAmount: billAmount, middleValue: middleValue).description
//and return in proper format
tipLabel.text = String(format: "%.2f", tip)

How do you use parse string in swift?

An issue here to me that if i use parse string for the result of calculator program for instance,
4.5 * 5.0 = 22.5
how can I use splitting here to depart decimal part from result?
Assuming you're working with strings only :
var str = "4.5 * 5.0 = 22.5 "
// Trim your string in order to remove whitespaces at start and end if there is any.
var trimmedStr = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// Split the string by " " (whitespace)
var splitStr = trimmedStr.componentsSeparatedByString(" ")
// If the split was successful, retrieve the last past (your number result)
var lastPart = ""
if let result = splitStr.last {
lastPart = result
}
// Since it's a XX.X number, split it again by "." (point)
var splitLastPart = lastPart.componentsSeparatedByString(".")
// If the split was successful, retrieve the last past (your number decimal part)
var decimal = ""
if let result = splitLastPart.last {
decimal = result
}
Use modf to extract decimal part from result.
Objective-C :
double integral = 22.5;
double fractional = modf(integral, &integral);
NSLog(#"%f",fractional);
Swift :
var integral:Double = 22.5;
let fractional:Double = modf(integral,&integral);
println(fractional);
Want only interger part from double of float
Want only integer value from double then
let integerValue:Int = Int(integral)
println(integerValue)
Want only integer value from float then
let integerValue:Float = Float(integral)
println(integerValue)

Resources