Wednesday, February 14, 2018

Cordova: Accepting user input

What would be the first thing in programming? A simple use of variable and user text input comes to mind. Following the previous post (link here), the Cordova programming environment is set up for Android. The existing files will be edited to do the following;

The HelloWorldApp when started, will prompt the user to enter a city name.






The user enters a city name and press "OK" button. The city name will be displayed on the app.






Step 1. Position the text to display user response.

Using a text editor, open the file index.html in HelloWorld/www and replace the previous <p> tag with the text "Hello World" with;

<div id="answer"></div>

Save the file.

Step 2. Prompt user at apps startup and display the reply.

Open the file index.js in HelloWorld/www/js

Add our function called getAnswer to the end of the file;
function getAnswer() {
    var ans = prompt("Name your city");
    if (ans.length > 0) {      
        document.getElementById('answer').innerHTML = "";      
        document.getElementById('answer').innerHTML = ans + " is a great place.";
    } else {      
        getAnswer();
    }
}


Activate the getAnswer function in the initialize:function( )by adding after document.addEventListener(...);

getAnswer( );

Step 3. Build and launch the app.

At the command line interface (CLI) or the command terminal, type

$ cordova build android
$ cordova run android

This will launch the default emulator.

In order to test the app, at any time after editing to the source files, just follow this Step 3.

Troubleshooting

Android emulator error: 
The connection to the server was unsuccessful. (file:///android_assets/www/index.html)

Edit the file config.xml in HelloWorld folder. Add the following line after the </platform> tag.

<preference name="loadUrlTimeoutValue" value="700000" />

Build and launch the app.

No comments:

Blog Archive