Refresh menu scene after data change (Corona SDK) - lua

I have just implemented adbuddiz reward video in my app and it works as expected but I have a slight challenge.
After watching the video, it triggers the "didComplete" event for adbuddiz where it adds the needed value into a json file.
The challenge now is the value does not automatically reflect on the screen except I go out of the scene and go back before the new value shows.
Is there a way to refresh the screen so the new value appears immediately?
Note: This all happens on a button click
local savecount = Lib.getSaveValue("savecount")
-- Events (rewarded video)
local function listenerRewardedVideo( event )
if event.value == "didFetch" then
print( "didFetch" )
end
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end
if event.value == "didNotComplete" then
print( "didNotComplete" )
end
if event.value == "didFail" then
print( "didFail - " .. event.detail )
end
end
Runtime:addEventListener( "AdBuddizRewardedVideoEvent", listenerRewardedVideo )
This displays the value on the menu scene
label_saveme = display.newText({parent=uiGroup, text=savecount, x=0, y=0, font=native.systemFont, fontSize=24})
label_saveme.xScale = 0.92
label_saveme.x = button_buysaveme.x + 22
label_saveme.y = button_buysaveme.y + 6
label_saveme:setFillColor(255/255, 255/255, 255/255)
label_saveme.alpha = 0.4
uiGroup:insert(label_saveme)
Thanks

So you want to put savecount value on label_saveme?
if your local label_save me on the same file as your button click code, change the "didComplete"
if event.value == "didComplete" then
print( "didComplete" )
-- Reward user here
print ("savecount")
savecount = savecount + 1
label_saveme.text = savecount
Lib.setSaveValue("savecount", savecount, true);
local alert = native.showAlert("Successful","Count saved successfully!", {"OK"})
end

Related

Corona interstitial tap count

i have a question with corona (LUA), at the moment im showing interstitial ad when tap button occurs. I have this and its working (sometimes takes like 5-10-15 seconds to load and ad, i dont know why:
local ads = require("ads")
local interstitialAppID = "ca-app-pub-xxxxxxxxxx/xxxxxxxx21"
local testMode = true
local adProvider = "admob"
local function adListener( event )
if ( event.isError ) then
print ( "Error en el anuncio!", msg )
elseif ( event.phase == "loaded") then
print ( "Anuncio cargado!", msg )
elseif ( event.phase == "shown") then
print ( "Cargando nuevo anuncio!", msg )
ads.load ("interstitial", { appId = interstitialAppID, testMode = isTestMode } )
end
end
ads.init("admob", interstitialAppID, adListener )
ads.load ("interstitial", { appId = interstitialAppID, testMode = isTestMode } )
-- INTERSTITIAL AD
local function Adinterstatial( self, event )
ads.show( "interstitial", { appId = interstitialAppID, testMode = isTestMode
} )
end
local test = display.newImageRect( "Lore/0.png", 50, 50 )
test.x = 150
test.y = 150
test.tap = Adinterstatial
test:addEventListener( "tap" )
I want to do this for example: every 20 taps (on all the app) shows an interistitial ad.
Is this possible?
How i can do it?
Thanks.
You can add a Runtime tap event. This will get all taps on the screen, it does not matter where or what object was tapped. For example:
local numTaps = 0
local function countTaps()
numTaps = numTaps + 1
if numTaps % 20 == 0 then
-- Show the add here.
end
end
Runtime:addEventListener("tap", countTaps)
The % gets the remaindeer of the division between numTaps and 20. This means that it will be 0 every 20 taps.

twitter not showing score properly - corona sdk

I am using twitter API to post highscores and it seems to be collecting the score variable correctly however, its not getting the highscore value on the turn that they played.
example: I start the game for first time and my highscore is 0. I get 20 on game over and want to tweet it but my tweet displays 0. on next play through it shows 20.
So its basically behind by 1 turn each time and displays the previous highscore. I have a feeling its a basic error but i can't see, to get around it.
I have two files that save my scores for leaderboards etc.
local scoring = require("helpers.scoring")
local utils = require("helpers.globals")
function scene:createScene( event )
local group = self.view
utils.loadHighscoreInfo()
-- Gameover --
if miles > utils.highscore then
utils.highscore = miles
utils.saveHighscoreInfo()
scoring.setHighScore( utils.highscore, utils.leaderboard )
end
-- Twitter set up --
local options = {
message = " I scored " .. utils.highscore .. " Miles ",
listener = tweetCallback
}
function tweetCallback( event )
if ( event.action == "cancelled" ) then
print( "User cancelled" )
else
native.showPopup( "twitter", options )
print( "Thanks for the tweet!" )
end
end
Update the options message before handling the tweet.
local options = {
message = " I scored " .. utils.highscore .. " Miles ",
listener = tweetCallback
}
This doesn't update dynamically as utils.highscore changes, it takes a snapshot of the value at the time you declare it (first run through each game). So you simply have to update it when the game is over using
options.message = "I scored" .. utils.highscore .. " Miles "

listener for multiple text field

I'm trying to call a text field listener from multiple field like this page
http://docs.coronalabs.com/api/library/native/newTextField.html#listener-optional
When user start to write something in input field, handler function is called normally but closure that is located in handler is not called.
login.lua file like below:
local storyboard = require( "storyboard" )
local scene = storyboard.newScene()
-- Forward declerations
local userNameField
-- TextField Listener
local function fieldHandler( getObj )
print( "This message is showing up :) " )
-- Use Lua closure in order to access the TextField object
return function( event )
print( "This message is not showing up :( There is something wrong here!!!" )
if ( "began" == event.phase ) then
-- This is the "keyboard has appeared" event
getObj().text = ""
getObj():setTextColor( 0, 0, 0, 255 )
elseif ( "ended" == event.phase ) then
-- This event is called when the user stops editing a field:
-- for example, when they touch a different field or keyboard focus goes away
print( "Text entered = " .. tostring( getObj().text ) ) -- display the text entered
elseif ( "submitted" == event.phase ) then
-- This event occurs when the user presses the "return" key
-- (if available) on the onscreen keyboard
-- Hide keyboard
native.setKeyboardFocus( nil )
end
end -- "return function()"
end
local function userNameFieldHandler( event )
local myfunc = fieldHandler( function() return userNameField end ) -- passes the text field object
end
-- Called when the scene's view does not exist:
function scene:createScene( event )
local group = self.view
-- Create our Text Field
userNameField = native.newTextField( display.contentWidth * 0.1, display.contentHeight * 0.5, display.contentWidth * 0.8, display.contentHeight * 0.08)
userNameField:addEventListener( "userInput", userNameFieldHandler )
userNameField.font = native.newFont( native.systemFontBold, 22 )
userNameField.text = "User Name"
userNameField:setTextColor( 0, 0, 0, 12 )
end
Help please...
I don't know Corona, but your code is somewhat strange.
userNameFieldHandler doesn't do much, it just creates a handler calling fieldHandler and stores it in a local that is never used (myfunc). Are you sure you didn't mean this:
local function userNameFieldHandler( event )
local myfunc = fieldHandler(
function() return userNameField end ) -- passes the text field object
return myfunc --<<<<--- added return
end
and maybe when you add the event listener you meant this (note the added ()):
userNameField:addEventListener( "userInput", userNameFieldHandler() )

Am not able to test inapp restore functionality in my version 2

I'v tested & uploaded my app on appStore it's inapp purchases was working perfectly fine, I was able to restore the app too.
But now I want to test it's version 2 but now am able to buy but restore isn't working.
module(..., package.seeall)
require("store")
require("ui")
local inappfile = require("inappfile")
local validProducts, invalidProducts = {}, {}
local listOfProducts =
{
-- These Product IDs must already be set up in your store
-- We'll use this list to retrieve prices etc. for each item
-- Note, this simple test only has room for about 4 items, please adjust accordingly
-- The iTunes store will not validate bad Product IDs
"com.tinytapps.pandamath.fullpack",
}
-------------------------------------------------
-- we store everything inside this group at the end
local newActivity = display.newGroup()
-----------------------------------------------------
---------------- IN APP CODE STARTS HERE ------------------
checkIfPurchased = function()
local filePath = system.pathForFile( "purchased.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
if file then
_G["isPurchased"] = true
--AdMediator.hide()
else
_G["isPurchased"] = false
--local_configuration()
end
end
callforpurchase = function()
if _G["isPurchased"] == false then
local cerateFile = function()
_G.noOfQuestionCompleted=0
local filePath = system.pathForFile( "purchased.txt", system.DocumentsDirectory )
local file = io.open( filePath, "r" )
print(file)
if file then
_G["isPurchased"] = true
io.close( file )
else
file = io.open( filePath, "w" )
_G["isPurchased"] = true
io.close( file )
end
end
function showTitle()
if isSimulator then
local myAlert = native.showAlert( "iTunes Store not available in Corona Simulator",
"Offline testing: see console for output.",
{ "OK" } )
end
end
-------------------------------------------------------------------------------
-- Product IDs should match the In App Purchase products set up in iTunes Connect.
-- We cannot get them from the iTunes store so here they are hard coded;
-- your app could obtain them dynamically from your server.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Process and display product information obtained from store.
-- Constructs a button for each item
-------------------------------------------------------------------------------
function unpackValidProducts()
local buttonSpacing = 5
-- Utility to build a buy button
-- Handler for buy button
function newBuyButton (index)
local buttonDefault = "add/buybtn.png"
local buttonOver = "add/buybtn.png"
local buyThis = function ( product )
print ("Purchasing " ..product)
-- Purchase the item
if store.canMakePurchases then
store.purchase( {product} )
else
native.showAlert("Store purchases are not available, please try again later",
{ "OK" } )
end
end
function buyThis_closure ( index )
-- Closure wrapper for buyThis() to remember which button
return function ( event )
buyThis (validProducts[index].productIdentifier)
return true
end
end
local hideDescription = function ( )
--descriptionArea.text = "Select a product..."
end
local describeThis = function ( description )
print ("About this product: " ..description)
end
function describeThis_closure ( index )
-- Closure wrapper for describeThis() to remember which button
return function ( event )
describeThis (validProducts[index].description)
return true
end
end
buyButton = ui.newButton{
default = buttonDefault, over = buttonOver,
onPress = describeThis_closure (index), onRelease = buyThis_closure (index),
}
_G.buyButton=buyButton
return buyButton
end
-- Utility to build a restore button
function newRestoreButton ()
local buttonDefault = "add/restorebtn.png"
local buttonOver = "add/restorebtn.png"
local restore = function ( product )
-- Ask the iTunes Store to initiate restore transaction sequence
print ("Restoring " )
store.restore()
end
local hideDescription = function ( )
--descriptionArea.text = "Select a product..."
end
local describeThis = function ()
-- Display info in description area
print ("Test restore feature")
end
--local label = "Test restore"
restoreButton = ui.newButton{
default = buttonDefault, over = buttonOver,
onPress = describeThis, onRelease = restore,
}
_G.restoreButton = restoreButton
return restoreButton
end
print ("Loading product list")
if not validProducts then
native.showAlert( "In App features not available", "initStore() failed", { "OK" } )
else
print ("Product list loaded")
print( "Country: " .. system.getPreference( "locale", "country" ) )
local buttonSpacing = 5
print( "Found " .. #validProducts .. " valid items ")
-- display the valid products in buttons
for i=1, #validProducts do
-- Debug: print out product info
print ("Item " .. i .. ": " .. validProducts[i].productIdentifier
.. " (" .. validProducts[i].price .. ")")
print (validProducts[i].title .. ", ".. validProducts[i].description)
---------------------------------------------------------------------------
-- create and position product button
local myButton = newBuyButton(i)
myButton.x = 570 --centerX - 200
myButton.y = 450 --centerY + 250
--myButton.xScale = 0.6
--myButton.yScale = 0.6
--newActivity:insert(buyButton)
myButton:toFront()
end
local restoreButton = newRestoreButton()
restoreButton.x = 200 --centerX + 200
restoreButton.y = 450 -- centerY + 250
--restoreButton.xScale = 0.6
--restoreButton.yScale = 0.6
--newActivity:insert(restoreButton)
restoreButton:toFront()
for i=1, #invalidProducts do
-- Debug: display the product info
native.showAlert( "Item " .. invalidProducts[i] .. " is invalid.",
{ "OK" } )
print("Item " .. invalidProducts[i] .. " is invalid.")
end
end
end
-------------------------------------------------------------------------------
-- Handler to receive product information
-- This callback is set up by store.loadProducts()
-------------------------------------------------------------------------------
function loadProductsCallback( event )
-- Debug info for testing
print("In loadProductsCallback()")
print("event, event.name", event, event.name)
print(event.products)
print("#event.products", #event.products)
io.flush() -- remove for production
-- save for later use
validProducts = event.products
invalidProducts = event.invalidProducts
unpackValidProducts ()
end
-------------------------------------------------------------------------------
-- Handler for all store transactions
-- This callback is set up by store.init()
-------------------------------------------------------------------------------
function transactionCallback( event )
local infoString
print("transactionCallback: Received event ", event.name)
if event.transaction.state == "purchased" then
cerateFile()
_G["isPurchased"] = true
--AdMediator.hide()
if buyButton ~= nil then
buyButton=nil
end
if restoreButton ~= nil then
restoreButton=nil
end
infoString = "Transaction successful!"
print (infoString)
inappfile.onClose()
print("transactionCallback() method called inappfile.onClose()")
elseif event.transaction.state == "restored" then
print ("Success! Product restored")
cerateFile()
_G["isPurchased"] = true
if buyButton ~= nil then
buyButton=nil
end
if restoreButton ~= nil then
restoreButton=nil
end
infoString = "Transaction successful!"
print (infoString)
inappfile.onClose()
print("transactionCallback() method called inappfile.onClose()")
elseif event.transaction.state == "cancelled" then
infoString = "Transaction cancelled by user."
elseif event.transaction.state == "failed" then
infoString = "Transaction failed, type: ",
event.transaction.errorType, event.transaction.errorString
else
infoString = "Unknown event"
end
-- Tell the store we are done with the transaction.
-- If you are providing downloadable content, do not call this until
-- the download has completed.
store.finishTransaction( event.transaction )
end
-------------------------------------------------------------------------------
-- Setter upper
-------------------------------------------------------------------------------
function setupMyStore (event)
store.loadProducts( listOfProducts, loadProductsCallback )
print ("After store.loadProducts, waiting for callback")
if isSimulator then
-- No Store, so no callbacks, so exercise our GUI "manually"
validProducts[1] = {}
validProducts[1].title = "Panda Math"
validProducts[1].description = "A wonderful product of Math for testing"
validProducts[1].price = 1.99
validProducts[1].productIdentifier = "com.tinytapps.pandamath.full"
unpackValidProducts()
end
end
-------------------------------------------------------------------------------
-- Main
-------------------------------------------------------------------------------
-- Show title card
showTitle ()
-- Connect to store at startup
store.init (transactionCallback )
print ("After init")
-- Hide title card, run store
timer.performWithDelay (1000, setupMyStore)
end
end

Remove items lua/Corona

Very quick, and probably easy question... but its left me stumped for the last 30 minutes... But how can I remove items from the canvas/screen?
I know this works with removeSelf(), but I'm not quite sure how to use that in my example:
display.setStatusBar( display.HiddenStatusBar )
function cat1()
displayCategory(1)
print( "clicked 1" )
end
function cat2()
displayCategory(2)
print( "clicked 2" )
end
function cat3()
displayCategory(3)
print( "clicked 3" )
end
--category display
function displayCategory(cat)
if (cat == nil) then
cat = 1
end
print( cat )
if (cat == 1) then
local item1 = display.newRect(100,100,100,100)
item1:setFillColor(255,255,0)
elseif (cat == 2) then
local item2 = display.newRect(200,100,100,100)
item2:setFillColor(255,0,255)
elseif (cat == 3) then
local item3 = display.newRect(300,100,100,100)
item3:setFillColor(0,255,255)
end
end
--category buttons
local catBtn1 = display.newRect(0,0,50,50)
catBtn1:setFillColor( 255,0,0 )
catBtn1:addEventListener( "tap", cat1 )
local catBtn2 = display.newRect(60,0,50,50)
catBtn2:setFillColor( 0,255,0 )
catBtn2:addEventListener( "tap", cat2 )
local catBtn3 = display.newRect(120,0,50,50)
catBtn3:setFillColor( 0,0,255 )
catBtn3:addEventListener( "tap", cat3 )
Right now, every time I click on of my buttons, the corresponding item pops up, but doesnt disappear when I click on any of the other buttons. How would I go about that?
First, create those itens on start, before the displayCategory function.
Then you set them to not visible, like this:
local item1 = display.newRect(100,100,100,100)
item1:setFillColor(255,255,0)
item1.isVisible = false
Later you set the proper itens to visible or not as appropriate, in case of item 2 it would be
item1.isVisible = false
item2.isVisible = true
item3.isVisible = false

Resources