.append in kotlin to showing expected result - android

I am building a calculator app, but when I clear the screen, the expression becomes 0. If I click a number then, it is appended to the expression(like, 05 instead of 5). Help me with the logic.
This is my code. 'string' is the button clicked( numbers(0,1,2,3,4,5,6,7,8,9) or operation(+, -, *, /) )
'Result.text' is the result screen text after calculation. 'Expression.text' is the expression build after clicking buttons.
Wrote a condition, if 'Expression.text' is 0, rewrite the text instead of appending the number.
'''
Result.text = ""
if (string == "0" ||string == "1" || string == "2" || string == "3" || string == "4" ||
string == "5" || string == "6" || string == "7" || string == "8" || string == "9"){
if(Expression.text == "0") {
Expression.text = string
}else {
Expression.append(string)
}
}else if (string == "+" || string == "-" || string == "/" || string == "*") {
while (Expression.text[Expression.text.length - 1] == '+' ||
Expression.text[Expression.text.length - 1] == '-' ||
Expression.text[Expression.text.length - 1] == '*' ||
Expression.text[Expression.text.length - 1] == '/'){
Expression.text = Expression.text.dropLast(1)
}
Expression.append(string)
}
'''

Related

I want to reset the tab and clear all fields after the button is pressed but the info is not being reset

There is add product button and on clicking that button the page moves to desired tab using pushnamed ..but i also want to reset the form present in the add product page..I am using form global key but formkey not resetting the form the data is still visible when I revisit that tab.. The following code snippet is provided above pls have a look..I tried using setstate used also text editing controller clear also but that passes empty string to firebase when I revisit that tab next time
The code-
void _trysubmit() async {
bool isvalid;
isvalid = _formGlobalKey.currentState!.validate();
if (isvalid) {
// ignore: non_constant_identifier_names
int days_calculation(DateTime day1, DateTime expirydate1) {
day1 = DateTime(day1.year, day1.month, day1.day);
expirydate1 =
DateTime(expirydate1.year, expirydate1.month, expirydate1.day);
final differenceInDays = expirydate1.difference(day1).inDays;
return differenceInDays;
}
try {
if (_pickedImage == null) {
_globalMethods.authErrorHandle('Please pick an image', context);
} else {
setState(() {});
final User? user = _auth.currentUser;
final _uid = user!.uid;
final ref = FirebaseStorage.instance
.ref()
.child('usersImages')
.child(_uid)
.child(_nameofproduct.text + '.jpg');
await ref.putFile(_pickedImage!);
url = await ref.getDownloadURL();
int uniqueid =
DateTime.now().millisecondsSinceEpoch.remainder(100000);
_formGlobalKey.currentState!.save();
Map<String, dynamic> data = {
"Name": _nameofproduct.text,
"Manufacturing Date": _dateController1.text,
"Expiry Date": day2 != null
? DateFormat('dd/MM/yyyy').format(day2!).toString()
: DateFormat('dd/MM/yyyy').format(day3!).toString(),
"Expiry Days": day2 != null
? days_calculation(DateTime.now(), day2!)
: days_calculation(DateTime.now(), day3!),
"Quantity": _quantitycontroller.text + " " + unit,
'Product Image': url,
"Category": category,
"Location": _location.text,
"Additional Information": _additionalinfo.text,
"Uniqueid": uniqueid,
};
FirebaseFirestore.instance
.collection('users')
.doc(_uid)
.collection("user_orders")
.add(data);
FirebaseFirestore.instance
.collection('users')
.doc(_uid)
.collection("user_orders")
.doc("count")
.update({category: FieldValue.increment(1)});
if ((day2 != null
? days_calculation(DateTime.now(), day2!)
: days_calculation(DateTime.now(), day3!)) <
2) {
createExpiryNotification(
uniqueid,
_nameofproduct.text,
NotificationCalendar(
year: DateTime.now().year,
month: DateTime.now().month,
day: DateTime.now().day,
hour: DateTime.now().hour,
minute: DateTime.now().minute + 2));
} else {
createExpiryNotification(
uniqueid,
_nameofproduct.text,
day2 != null
? NotificationCalendar(
year: day2!.subtract(const Duration(days: 1)).year,
month: day2!.subtract(const Duration(days: 1)).month,
day: day2!.subtract(const Duration(days: 1)).day,
hour: 10,
minute: 0)
: NotificationCalendar(
year: day3!.subtract(const Duration(days: 1)).year,
month: day3!.subtract(const Duration(days: 1)).month,
day: day3!.subtract(const Duration(days: 1)).day,
hour: 10,
minute: 0));
}
if (category == 'Bakery') {
_formGlobalKey.currentState?.reset();
widget.navigatorKey1.currentState!.pushNamed("Bakery");
} else if (category == 'Dairy') {
widget.navigatorKey1.currentState!.pushNamed("Dairy");
} else if (category == 'Medicine') {
widget.navigatorKey1.currentState!.pushNamed("Medicine");
} else if (category == 'Frozen Food') {
widget.navigatorKey1.currentState!.pushNamed("Frozen Food");
} else {
widget.navigatorKey1.currentState!.pushNamed("Others");
}
//clearformfield();
_formGlobalKey.currentState?.reset();
widget.controller1.index = 0;
}
} finally {
setState(() {});
}
}
}
This is the page at startup
This is the page after info is filled

How to detect hold and fastforward event in react native TVEventHandler

I am new to React Native. I want to know how can implement press and hold event for seek.
I am able to get fastForward and press right events in React native layer by using below code.
_enableTVEventHandler() {
this._tvEventHandler = new TVEventHandler();
this._tvEventHandler.enable(this, function(cmp, evt) {
if (evt && evt.eventType === 'right') {
cmp.setState({board: cmp.state.board.move(2)});
} else if(evt && evt.eventType === 'up') {
cmp.setState({board: cmp.state.board.move(1)});
} else if(evt && evt.eventType === 'left') {
cmp.setState({board: cmp.state.board.move(0)});
} else if(evt && evt.eventType === 'down') {
cmp.setState({board: cmp.state.board.move(3)});
} else if(evt && evt.eventType === 'playPause') {
cmp.restartGame();
}
});
}
Not able to get the hold fastforward or hold and right event to detect seek event. I am not sure it if its possible in RN layer. If not then how can i do the same in Android layer.
Thanks in advance
you could try something like this where eventKeyAction is an integer value that represents button press(down/up).where "key up" is 1, "key down" is 0.
so you could use that to serve your purpose
const [isfastForwarding, setisfastForwarding] = useState(false);
const _enableTVEventHandler = () => {
_tvEventHandler = new TVEventHandler();
_tvEventHandler.enable(this, (cmp, { eventType, eventKeyAction }) => {
// eventKeyAction is an integer value representing button press(key down) and release(key up). "key up" is 1, "key down" is 0.
if (eventType === "fastForward" && eventKeyAction === 0) {
setisfastForwarding(true);
}
if (eventType === "fastForward" && eventKeyAction === 1) {
setisfastForwarding(false);
}
});
};
you can also add some delay if you wish to

Properly remove a scrollView in Corona SDK

In my game I have a scrollview widget declared inside a function, and I want to remove that scrollview using another function, something like this:
local function createScrollView(event)
if(event.phase=="ended")then
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
--print( "Began" )
elseif "moved" == phase then
print( "Moved" )
elseif "ended" == phase then
--print( "Ended" )
end
-- If the scrollView has reached it's scroll limit
if event.limitReached then
if "up" == direction then
print( "Reached Top Limit" )
elseif "down" == direction then
print( "Reached Bottom Limit" )
elseif "left" == direction then
print( "Reached Left Limit" )
elseif "right" == direction then
print( "Reached Right Limit" )
end
end
return true
end
-- Create a ScrollView
local scrollView = widget.newScrollView
{
left = display.contentWidth/2-130,
top = display.contentHeight/2-165,
width = 440,
height = 300,
bottomPadding = 10,
id = "onBottom",
backgroundColor = { 0, 0, 0, 0 },
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
}
end
end
local function removeScrollView(event)
if(event.phase==ended)then
if scrollView then
scrollView:removeSelf()
scrollView = nil
end
end
end
It doesn't return any error, but I can see that the scrollView still exists because the Corona Terminal keeps printing "moved".
Do you know how could I remove it?
local scrollView ------------EDITED
local function createScrollView(event)
if(event.phase=="ended")then
local function scrollListener( event )
local phase = event.phase
local direction = event.direction
if "began" == phase then
--print( "Began" )
elseif "moved" == phase then
print( "Moved" )
elseif "ended" == phase then
--print( "Ended" )
end
-- If the scrollView has reached it's scroll limit
if event.limitReached then
if "up" == direction then
print( "Reached Top Limit" )
elseif "down" == direction then
print( "Reached Bottom Limit" )
elseif "left" == direction then
print( "Reached Left Limit" )
elseif "right" == direction then
print( "Reached Right Limit" )
end
end
return true
end
-- Create a ScrollView
---EDITED---------------------
scrollView = widget.newScrollView
{
left = display.contentWidth/2-130,
top = display.contentHeight/2-165,
width = 440,
height = 300,
bottomPadding = 10,
id = "onBottom",
backgroundColor = { 0, 0, 0, 0 },
horizontalScrollDisabled = true,
verticalScrollDisabled = false,
listener = scrollListener,
}
end
end
local function removeScrollView(event)
if(event.phase==ended)then
if scrollView then
scrollView:removeSelf()
scrollView = nil
end
end
end
So that you can remove the scroll view in the removeScrollView function.

Multitouch detection with holding event Corona SDK

I have this big issue, and im so pissed off because of this. I have no idea anymore how to make a function that handles touching more than one object. To introduce what i have and what should it do.
I have 3 objects, two buttons: LEFT and RIGHT. and SHOOTING button. I need to be able to shoot while holding the rotating button. I have this (code below) and it does work but if i touch shooting button it stops rotating.
local isShooting = false
function resetShooting()
isShooting = false
end
function holdingLeft()
if isPressed == true then
if rotationOfship > 0 then
if touchedXTimes < 10 then
rotationOfship = rotationOfship-2
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
elseif touchedXTimes > 9 then
rotationOfship = rotationOfship-5
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
elseif touchedXTimes > 29 then
rotationOfship = rotationOfship-8
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
end
else
rotationOfship = 360
end
elseif isPressed == false then
timer.cancel(tmr_hold)
end
end
function holdingRight()
if isPressed == true then
if rotationOfship < 360 then
if touchedXTimes < 10 then
rotationOfship = rotationOfship+2
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
elseif touchedXTimes > 9 then
rotationOfship = rotationOfship+5
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
elseif touchedXTimes > 29 then
rotationOfship = rotationOfship+8
touchedXTimes = touchedXTimes + 1
ship.rotation = rotationOfship
end
print(touchedXTimes)
else
rotationOfship = 0
end
elseif isPressed == false then
timer.cancel(tmr_hold)
end
end
function onTouch(event)
if event.target.name == "left" then
if event.phase == "began" then
isPressed = true
display.getCurrentStage():setFocus( event.target )
event.target.isFocus = true
if tmr_hold ~= nil then timer.cancel(tmr_hold) end
tmr_hold = timer.performWithDelay( 8, holdingLeft, 0)
elseif event.target.isFocus then
if event.phase == "ended" or event.phase == "cancelled" then
isPressed = false
timer.cancel(tmr_hold)
touchedXTimes = 0
display.getCurrentStage():setFocus( nil )
event.target.isFocus = false
end
end
end
if event.target.name == "right" then
if event.phase == "began" then
isPressed = true
display.getCurrentStage():setFocus( event.target )
event.target.isFocus = true
if tmr_hold ~= nil then timer.cancel(tmr_hold) end
tmr_hold = timer.performWithDelay( 8, holdingRight, 0)
elseif event.target.isFocus then
if event.phase == "ended" or event.phase == "cancelled" then
isPressed = false
timer.cancel(tmr_hold)
touchedXTimes = 0
display.getCurrentStage():setFocus( nil )
event.target.isFocus = false
end
end
end
if event.target.name == "laser" then
if event.phase == "began" and isShooting == false then
isShooting = true
display.getCurrentStage():setFocus( event.target )
event.target.isFocus = true
bullet = display.newImageRect("images/laser.png",math.random(5,20),5/2)
bullet.x = halfW
bullet.y = halfH
bullet.name = "bullet"
bullet.rotation = rotationOfship-90
physics.addBody( bullet, "dynamic", { isSensor=true, radius=10} )
group:insert(bullet)
ship:toFront()
audio.play( laserSound, { channel=2, loops=0} )
local newX, newY = pointAtDistance(rotationOfship-90, 400)
bullet:setLinearVelocity( newX/2, newY/2 )
tmr_shoot = timer.performWithDelay( math.random(300,400), resetShooting, 1)
elseif event.target.isFocus then
if event.phase == "ended" or event.phase == "cancelled" then
isShooting = false
timer.cancel(tmr_shoot)
display.getCurrentStage():setFocus( nil )
event.target.isFocus = false
end
end
end
return true
end
dpad_left_circle:addEventListener( "touch", onTouch )
dpad_right_circle:addEventListener( "touch", onTouch )
laser_button_circle:addEventListener( "touch", onTouch )
I would recommend to split it to three methods instead of one:
dpad_left_circle:addEventListener( "touch", onTouchLeft )
dpad_right_circle:addEventListener( "touch", onTouchRight )
laser_button_circle:addEventListener( "touch", onTouchLaser )
Code will be much more clear and you'll be able to touch different buttons at the same time.

Button Click of my Android App using Sencha Touch 2 is working fine in Android 2.3 emulator but not working properly in Android 3.0 and above [duplicate]

This question already exists:
Button click in Android app using Sencha Touch 2 running fine on emulator but not working on Android Device
Closed 10 years ago.
Button Click of my Android App using Sencha Touch 2 is working fine in Android 2.3 emulator but not working properly in Android 3.0 and above.When I am running this app in Android 3.0 and above and click Save button it doesn't compile from var isValid = true; line. My code is as follows:-
{
xtype: 'button',
text: 'Save',
handler: function(){
//var val3 = Ext.ComponentQuery.query('#na')[0].getValue();
val3 = Ext.getCmp('na').getValue();
console.log(val3);
val = Ext.getCmp('ea').getValue();
console.log(val);
val4 = val.indexOf("#");
console.log(val4);
val5 = val.lastIndexOf(".");
console.log(val5);
val2 = Ext.getCmp('pa').getValue();
console.log(val2);
val1 = Ext.getCmp('ra').getValue();
console.log(val1);
var isValid = true;
Ext.Msg.alert("Info", "123");
var errors = new Array();
Ext.Msg.alert("Info", "456");
//validate the name
if (val3.search(/[0-9]/) > -1) {
Ext.Msg.alert("Info", "789");
isValid = false;
errors.push({field : 'name',
reason : 'Name must not contain numbers'});
}
if (val3.length <= 0) {
isValid = false;
errors.push({field : 'name',
reason : 'Name should not be blank'});
}
if (val3.search(/[#]/) > -1) {
isValid = false;
errors.push({field : 'name',
reason : 'Name must not contain special characters'});
}
//validate e-mail
if (val4<1 || val5<val4+2 || val5+2>=val.length)
{
isValid = false;
errors.push({field : 'email',
reason : 'Invalid email id'});
}
if (val.search("/^([a-zA-Z0-9_\.\-])+(#[a-z])+([.][a-z])+$+") > -1){
isValid = false;
errors.push({field : 'email',
reason : 'Invalid Email address'});
}
if (val.length <= 0){
isValid = false;
errors.push({field : 'email',
reason : 'Email address should not be blank'});
}
//validate Password
if (val1 != val2) {
isValid = false;
errors.push({field : 'reenter',
reason : 'Password do not match'});
}
if(val2 <= 0){
isValid = false;
errors.push({field : 'password',
reason : 'Password should not be blank'});
}
if(val1 <= 0){
isValid = false;
errors.push({field : 'reenter',
reason : 'Re-enter Password should not be blank'});
}
if(val1.length > 4){
isValid = false;
errors.push({field : 'reenter',
reason : 'Re-enter Password should not be more than 4 characters'});
}
if(val2.length > 4){
isValid = false;
errors.push({field : 'password',
reason : 'Password should not be more than 4 characters'});
}
//show error if the validation failed
if (!isValid) {
var errStr = "";
Ext.each(errors, function(error, index){
errStr += "[" + (index+1) + "] - " + error.reason + "\n";
});
Ext.Msg.alert("Error", errStr);
} else {//form is valid
//form.submit();
Ext.Msg.alert("Info", "Success");
}
}
I hate to be the one to break the news to you, but Sencha Touch 2 does not support Android 3.x. Only 2.x and 4.x. A quick forum discussion can be found here:
http://www.sencha.com/forum/showthread.php?186178-Phonegap-1.5-Sencha-Touch-2-has-problems-on-android-3.0
Your syntax looks fine though.

Categories

Resources