Reputation: 1
im new to corona and im trying to pull data from mysql database and use that data in the app.
the data fetches correctly but i can access it outside the function.
The function to get the data:
function loginCallback(event)
if ( event.isError ) then
print( "Network error!")
else
print ( "RESPONSE: " .. event.response )
local data = json.decode(event.response)
if data.result == 200 then
media = data.media_plats
print("Data fetched")
else
print("Something went wrong")
end
end
return true
end
and then i want to access it here:
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
elseif phase == "did" then
-- make JSON call to the remote server
local URL = "http://www.mywebsite.com/temp_files/json.php"
network.request( URL, "GET", loginCallback )
print(data.media_plats) -- returns nil
end
end
Thanks in advance.
Upvotes: 0
Views: 79
Reputation: 6251
your callback is invoked asynchronously so network.request
will return immediately and probably before the request result has comes back.
If you want to use data.media_plats
(even printing), it should be done/triggered inside the callback.
data is declared as local
in the callback so it wont be available outside the function. You can either remove the local
to make data a global variable, but maybe that is why you have media = data.media_plats
and so printing outside the function with print(media)
is probably what you wanted.
.
You can try something like this as a start. It sends the request and the callback triggers a method on the scene to update itself with the newly arrived data. Usually you would set up the view with some placeholder data and let the user know your waiting on data to arrive with a progress indicator of some sort.
Disclaimer: I do not use Corona.
-- updates a scene when media arrives
local function updateWithResponse(scene, media)
local sceneGroup = self.view
local phase = event.phase
print(media)
-- display using show after
end
--makes a request for data
function scene:show( event )
if phase == "will" then
elseif phase == "did" then
-- make JSON call to the remote server
local URL = "http://www.mywebsite.com/temp_files/json.php"
network.request( URL, "GET", responseCallback(self))
end
end
-- when media arrives, calls function to update scene.
local function responseCallback(scene)
return function ( event )
if ( event.isError ) then
print( "Network error!" )
elseif ( event.phase == "ended" ) then
local data = json.decode(event.response)
if data.result == 200 then
print("Data fetched")
-- finish setting up view here.
scene:updateWithResponse(data.media_plats)
else
print("Something went wrong")
end
end
end
end
Upvotes: 1