Click here to Skip to main content
15,867,453 members
Articles / Mobile Apps

Beginning Hybrid Mobile App Development with Corona SDK

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
28 Aug 2015CPOL12 min read 16.3K   2   2

Download HelloMash.rar

Download HelloMash_3.rar

Introduction

I have always been interested in how they do that when it comes to game development for mobile devices. A couple of months ago, I ran into the Corona SDK, skimmed a few ebooks but was interested in the mobile app development part of it more than the game part of it for now. I must say this SDK gives a punch when it comes to mobile app development because of its ease of use. It's a platform that you are able to write once and then it spills out your iOS and Android app without hustles. The backbone language of choice is something called Lua, a programming language that I didn't even know existed.

Quote:
Corona SDK and Lua - a joy in a long time.

As this is just a beginning article, don't expect to be developing an app with bells and whistles yet after this introduction. The nice thing is, you dont have to have Java knowledge or XCode to write a simple basic app. I will show you how we will write a simple Hello World app for the Android platform and how we can then compile it to an apk. The focus of this article will be for the android platform. For the iOS you can just run the same code and everything should be super. I will write an article for the iOS execution once I have an mac book or rent one online.

For this article, we will create a simple android app with one screen to show a label with Hi Dad on it and a background image. This is going to be less than 50 lines of code, no XCode, no Java, just simple Lua. The Corona SDK has also a wealth of plugins that one can use in development of their apps. With that there is Corona University where one can learn more about the language and the sdk for more powerful applications. I discovered a wealth of information on the Guides for my initial learning into this new world.

Some silly assumptions: You are familar with events and their listeners. You have some computer programming experience e.g. variable definition and scope. You are not familiar with xcode and or have done some android programming or have / will create keystroke files.

Background

The way Corona built apps work was simple for me to understand including parts of the Lua language.

1. You have a config.lua file that stores important information about the configuration of your app, like width and height of the screen, the orientation to use, frames per second etc.

2. Secondly you always got to have the main.lua file. When an Corona SDK app starts, it always looks for the main.lua file to execute first.

3. For any additional screens in your app, you can create additional lua files and set them up to do what you want. These can have names like dad.lua, mom.lua, home.lua etc.

Using the code

For one to be able to develop Corona SDK apps, there are some few requirements that must be met. First you need to download the Corona SDK itself and also the Java SDK 32bit version.

1. Download the Corona SDK here.

2. Have a text editor like NotePad++, you can also use Eclipse to do this and set up a Corona SDK plugin in it.

3. For the purposes of this exercise, we will use my own created tool, Corona.Show, a java app I created to create a simple introductory mobile app. This of course is a cheat app as it's a RAD tool. I was just lazy to have to write code all over again whilst I would just RAD it and started working on this tool. It's still in it's infacy though.

4. To compile your app to an apk, you will need an internet connection as the app will be compiled by the CoronaLabs servers and dumped on your folder.

I would greatly recommend that if you are interested in this Corona SDK world to purchase the book Learning Mobile App & Game Development with Corona. My cousin came to my rescue and got it for me and its such an invaluable source of learning. He calls it a "business investment". Love that term.

After installing the Corona SDK, if all is well, you should see an icon named "Corona Simulator" on your desktop. That is what you will use to create your Corona SDK app.

Image 1

Fire up the application and you should see something like this.

Image 2

We will create a new project, select New Project. There is a variety of projects that you can create like tabbed applications, blank application, multi-scene application. For the purpose of this article, just select Multiscene Application.

Image 3

I will call my application, HelloMash. Type your application name in Application Name, click Ok. As soon as you click Ok, the Corona SDK will create a multi-scene application for you in the project folder and simulate it. This is the beauty that I love about this framework.

On View, View As, I selected iPhone 6 Plus and this was simulated, you can change to the various device simulators if you want and the app will follow your commands.

Image 4

As you click "Go to Scene2" etc, the app will move from one scene to another back and forth. On the opened folder structure by the SDK, you will notice a variety of pngs and lua files being main.lua, config.lua, scene1.lua, scene2.lua and scene3.lua. Lets look into these files in detail.

config.lua

As indicated before, the config.lua file stores app configuration settings. In its simplest form, the file looks like this.

application =
{
 content =
 {
  width = 320,
  height = 480, 
  scale = "letterBox",
  fps = 30,
 },
}

This tells the sdk that the width of the app will be 320 and height 480 and the scale letterBox with fps (frames per second) 30. The Corona SDK is a game development framework thus fps. This file should be in the same folder as the main.lua file. Its purpose is to ensure that your app is properly scaled for the various different devices available. The scale can be none, letterBox (scale evenly), zoomEven (uniform screen) and zoomStretch (all content on screen).

main.lua

If there is no main.lua file in your project folder, your app will not run.

-- hide the status bar
display.setStatusBar( display.HiddenStatusBar )
-- require the composer library
local composer = require "composer"
-- load scene1
composer.gotoScene( "scene1" )

From the above code, we see our comments starting with --. The line after that tells the app to hide the status bar, then use the composer library. The composer library is used for screen navigation. There is also a storyboard library for that but we will discuss that on another day. Thereafter the app should show scene1 screen. The statusbar parameters work on iOS and the status bar can be set to be dark, default, translucent and hidden.

scene1.lua and others

local sceneName = ...
local composer = require( "composer" )
-- Load scene with same root filename as this file
local scene = composer.newScene( sceneName )
local nextSceneButton
function scene:create( event )
    local sceneGroup = self.view
    -- Called when the scene's view does not exist
    -- 
    -- INSERT code here to initialize the scene
    -- e.g. add display objects to 'sceneGroup', add touch listeners, etc
end
function scene:show( event )
    local sceneGroup = self.view
    local phase = event.phase
    if phase == "will" then
        -- Called when the scene is still off screen and is about to move on screen
        local title = self:getObjectByName( "Title" )
        title.x = display.contentWidth / 2
        title.y = display.contentHeight / 2
        title.size = display.contentWidth / 10
        local goToScene2Btn = self:getObjectByName( "GoToScene2Btn" )
        goToScene2Btn.x = display.contentWidth - 95
        goToScene2Btn.y = display.contentHeight - 35
        local goToScene2Text = self:getObjectByName( "GoToScene2Text" )
        goToScene2Text.x = display.contentWidth - 92
        goToScene2Text.y = display.contentHeight - 35
    elseif phase == "did" then
        -- Called when the scene is now on screen
        -- 
        -- INSERT code here to make the scene come alive
        -- e.g. start timers, begin animation, play audio, etc
        -- we obtain the object by id from the scene's object hierarchy
        nextSceneButton = self:getObjectByName( "GoToScene2Btn" )
        if nextSceneButton then
         -- touch listener for the button
         function nextSceneButton:touch ( event )
          local phase = event.phase
          if "ended" == phase then
           composer.gotoScene( "scene2", { effect = "fade", time = 300 } )
          end
         end
         -- add the touch event listener to the button
         nextSceneButton:addEventListener( "touch", nextSceneButton )
        end
    end 
end
function scene:hide( event )
    local sceneGroup = self.view
    local phase = event.phase
    if event.phase == "will" then
        -- Called when the scene is on screen and is about to move off screen
        --
        -- INSERT code here to pause the scene
        -- e.g. stop timers, stop animation, unload sounds, etc.)
    elseif phase == "did" then
        -- Called when the scene is now off screen
  if nextSceneButton then
   nextSceneButton:removeEventListener( "touch", nextSceneButton )
  end
    end 
end
function scene:destroy( event )
    local sceneGroup = self.view
    -- Called prior to the removal of scene's "view" (sceneGroup)
    -- 
    -- INSERT code here to cleanup the scene
    -- e.g. remove display objects, remove touch listeners, save state, etc
end
-- Listener setup
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )
return scene

If you study the lua source code above, you will discover that the code is self explanatory. There are events that happen when a screen comes to life. These are create, show, hide and destroy. The corona sdk needs to trap these events when they happen and perform the various actions, thus the addition of event listeners. Event listeners can be added to any type of control for it to have actions associated with it.

On scene create, create your controls that you want to see in your screen. On scene show, add some more functionalities to your controls e.g. move them around etc. Scene show has two phases, will and did. Will is when show is about to happen and did is when the scene has now been shown. Scene hide also has two phases, about to hide by will and did when hidden. There are various actions that you can undertaken in your app during these phases too.

For someone who is new to this, most of this code above might seem daunting and complicated, it did to me too. I was like WT? and where is Left, Top, Width, Height properties for controls that I was accustomed to. So I started working on the development of Corona.Show, a RAD tool I intend building up to ease the process of developing my Corona Apps.

You will note that there are "local" words within the lua code above. These are the same as var in JavaScript or Dim in Vb. These are for declaring variables, but local here means the scope of the variable. Global variables are either defined without the local or global is used. For more details about variables and scope check the Lua documentation. There is also x and y properties within the variables. Think of these as the x and y co-ordinates as in maths. Don't worry, I'm not very good at maths, so they still confuse me, but I got a way around that by using anchoring.

You will notice that within the project folder, these is also another file calles scene1.ccscene. This files holds the definition of the controls within scene 1.

{
    "metadata": {
        "creator": "Corona Composer", 
        "version": "0.6"
    }, 
    "objects": {
        "id1": {
            "alpha": 1, 
            "bgColor": {
                "b": 0.87843137254902, 
                "g": 0.72156862745098, 
                "r": 0.55294117647059
            }, 
            "children": [
                "id2", 
                "id3", 
                "id4", 
                "id5"
            ], 
            "drawMode": "normal", 
            "gridH": 20, 

A brief look into this file details how the app is built using the Corona Composer GUI. At the time of writing, the Composer is only available for the MAC platform. For Windows users like us, fortunately, I am working on a GUI tool, but which is still at infancy and would possibly not even come close to a windows based composer, but due to curiosity and awe at this framework, I decided why not. Let's create a simple app using Corona.Show then to demostrate this.

Compiling your app to APK.

1. Ensure you have an internet connection.

2. In your Corona Simulator, click File > Build for Android > Build.

Image 5

This stackoverflow article explains how you can create keystrokes.

Using Corona.Show

1. Create a folder in your C:\ drive and drop Corona.jar there. To use this you will need the Java SDK, download that too (see link above)

2. If all goes well, you should see this screen.

Image 6

3. Click File > New and enter the project details. Lets specify the project as HelloMash or whatever you prefer.

4. Leave everything as is for now and click Next. This will show the next screen for your scenes. The app has created a main scene for you. This will be linked to main.lua.

Image 7

5. Change the BG Color to while by selecting white from the ColorPicker. Click Apply.

Now lets add another scene to our app that will show Hi Dad!.

6. Click File > New. Type in the scene name as dad and select a BG image from your selection of pictures

7. Check Starting Scene to be on. That tells our RAD that dad will be the starting scene that main will open after starting

8. Check Composer to be on as we will use that for screen navigation. Click Appy.

Let's finalize the dad.lua screen.

9. Select dad from the scene list on the left.

10. Click Insert > Text

Image 8

11. Change the ID to be lblID, change Text to be Hi Dad, font to be bold and font size to be 24. Leave the color to be white.

12. Click Apply. You have just created a label to be placed in the dad scene at left 10 top 50.

13. Click File > Exit, you should be in the Project Screen.

14. Click File > Compile in the project screen. This will open up your project files.

Start the Corona Simulator if its not started and select Open Project.

In the folder where you saved CoronaShow.jar, locate the Apps folder.

Select the Folder that is your Application name, e.g. HelloMash

Select main.lua there and the simulator should run your app. If all goes well, you should see a screen like this (with your own background)

Image 9

Let's look at our version of the app...

HelloMash Project - config.lua

--calculate the aspect ratio of the device:
application = 
{
showRuntimeErrors = false,
content = 
{
width = 320,
height = 480,
scale = "letterBox",
xAlign = "left",
yAlign = "top",
fps = 30,
imageSuffix = {
["@2x"] = 2,
}
},
}

You can compare this config with the one above, the only difference is the showRuntimeErrors property.

HelloMash Project - main.lua

display.setDefault("background", 0,0,0)
-- set the status bar of the app iOS
display.setStatusBar(display.DefaultStatusBar)
local composer = require "composer"
-- useful functions
composer.gotoScene("dad", {effect="fade", time = 400})
  • Here we set the background to be black using RBG values. Corona uses RGB for colors.
  • The status bar is set as default. You can change this whilst developing with Corona.Show as depicted above.
  • We will use the composer library for screen navigation
  • When the app starts, the dad screen / scene should be shown, after 400 miliseconds with a fade transition.

HelloMash Project - dad.lua

Our mobile app was created with Corona.Show this time around. You will note similarities with the scene1.lua file as discussed above here, but ours does not have a dad1.ccscene file as we are not using the composer. Within our scene create, we create the screen controls as depicted below.

function scene:create(event)
    -- create a group to hold everything in the scene
    local sceneGroup = self.view
    bgImage = display.newImage("61045423.jpg",0,0)
    sceneGroup:insert(bgImage)
    lblDad = display.newText("Hi Dad",0,0,100,40,native.systemFontBold,24)
    lblDad.anchorX = 0
    lblDad.anchorY = 0
    lblDad.x = 10
    lblDad.y = 50
    lblDad:setTextColor(255,255,255)
    sceneGroup:insert(lblDad)
end
  • Each scene has a group object which is the self.view itself. We can reference this and add controls to it.
  • We defined our scene to have a background image, we insert this image to the scene
  • We defined a lblDad text label when we used our RAD with some properties, these have been translated to this. I am coming from a world of Left, Top, Width and Height, so I opted for that approach and left x=0 and y=0 at first and then set anchors for the left and top position of the label.
  • With the color of the label to be white, i used rgb 255 for that.

The book referenced above follows this approach in development. Perhaps a Corona Composer book will be released sometime. You can find more information about the display objects from the CoronaLabs here.

Points of Interest

As indicated, Corona.Show is still in its infancy and more controls will be added as we go along. It was conceptualized, designed and developed with a need to design Corona SDK apps easily and currently no aspirations on game development yet. There is still a lot that I have to learn about Corona SDK to be flexible enough on my side but it has been both a challenging and an exciting world. I cannot wait to test my created apps from an iOS perspective.

Peach Pellen here in CodeProject has also an interesting interview on this sdk and her blog has proved a valuable place to learn from.

Watch this space for more developments on my experiences about the Corona SDK Mobile App Development.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer SITHASO HOLDINGS (PTY) LTD
South Africa South Africa
I'm a Bachelor of Commerce graduate, fell inlove with ICT years back with VB5. Used Pick & System Builder to create a windows app. Very curious, developed my first web database app called Project.Show using ExtJS. Published on Google Play Store, learned JQuery Mobile, a project manager at best. My first intranet app eFas with MySQL.

Fear closes people to a lot of things and we hold ourselves back being held by it. Thus the sooner you believe you can't do something, the sooner everything will work towards that belief. Believe in yourself at all times because you can do anything you set your mind to it!

I have a very beautiful woman and four kids, the best joys in the world. East London, South Africa is currently home.

Awards:

Best Mobile Article of February 2015 (First Prize)
http://www.codeproject.com/Articles/880508/Create-a-CRUD-web-app-using-JQuery-Mobile-and-Loca

Best Mobile Article of May 2015 (Second Prize)
http://www.codeproject.com/Articles/991974/Creating-JQuery-Mobile-CRUD-Apps-using-JQM-Show-Ge

Apps
Bible.Show (Android Store App)
https://www.facebook.com/bibleshow
https://play.google.com/store/apps/details?id=com.b4a.BibleShow

JQM.Show (Android Store App)
https://www.facebook.com/jqmshow
https://play.google.com/store/apps/details?id=com.b4a.JQMShow

CodeProject.Show (An offline CodeProject Article writer)
http://www.codeproject.com/Articles/993453/CodeProject-Show-A-CodeProject-offline-article-wri

Comments and Discussions

 
QuestionVery nice! Pin
Paul Conrad5-Sep-15 18:00
professionalPaul Conrad5-Sep-15 18:00 
AnswerRe: Very nice! Pin
Anele 'Mashy' Mbanga8-Sep-15 11:27
professionalAnele 'Mashy' Mbanga8-Sep-15 11:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.