Linux Format

Android apps

The ever-intrepid Kent Elchuk takes you on another gold-seeking ride along Cordova Alley for building that next Android app. Hold on tight!

- Kent Elchuk is an experience­d web developer who’s built many web applicatio­ns for high schools, colleges, small businesses and personal pleasure.

Kent Elchuk is on a gold-seeking ride down Cordova Alley for building that next Android app.

Back in issue LXF225, we covered how to set up Linux and build very basic Cordova apps. This time, we will take things up a notch and make an app that can do more than just open a web page from an app button.

By the time you get to the end of this short article, you’ll know how to build an Android app using Cordova that will be able to do a range of tasks: from using the Wordpress REST api to return json strings and getting images from your camera and sending them to a remote server.

The first step to building an app is to use the cordova create command. If you have already built a simple Cordova app in the past, or have read my previous article about Cordova apps and followed instructio­ns, you should be good to go. If not, don’t worry – visit https://cordova.apache.org/ docs/en/latest/guide/cli/ to find out how to set your machine up. In this tutorial, there’ll be references made to the NetBeans editor. You can download it at https://netbeans. org/downloads/.

So, before starting this tutorial, you should be able to create a simple Android app with your system and edit it with NetBeans. Moving on from the various basic setup details, let’s go into more details about building an app with multiple pages. Note that this procedure will be covered from beginning to end, including the initial installati­on from the command line.

The app you’re about to build will have several pages that will do various tasks. For example, one page will be a REST api that lists all the posts from a Wordpress site. The titles with be linkable and you can open them up as you see fit.

So, let’s start by installing a Jquery mobile app via the command line with a list view for our several page.

The first step is to add the cordova-jquery module: sudo npm install -g cordova-jquery

After that, you use the cordovacre­ate command followed by the folder name you want for the project, followed by a few more commands as demonstrat­ed below. cordova create jquery_mobile cd jquery_mobile cordova-jquery

When prompted “Would you like to add jQuery mobile…” type Y and hit Enter. After that, you’ll be asked what to do. Select ‘applyTempl­ate’. After that, choose listView. Then, type Y to keep the code.

That’s it. Now you can add the Android platform, build it and test it in your Android phone. cordova platform add android cordova build cordova run android

As you can see, the app opens up with a clean menu and three pages. All three pages for the app exist in the file www/index.html.

If you take a brief look, you can see that Jquery mobile uses data-role=”page” and individual page ids for each page. In the case of these three pages, the individual page ids for each page are page1, page2 and page3.

Now, you can easily make a clean-looking app. However, you can go a step further and add a CSS framework such as

Bootstrap for your coding endeavour. Adding Bootstrap is just a matter of adding bootsrap.min.css to the www/css folder and bootstrap.min.js to the www/js folder.

Another way to get Bootstrap is to make a Cordova app with NetBeans with the Twitter Bootstrap template and copy the files from the css and js folders. You simply click each file while holding down the Ctrl key. Then right-click copy and paste them to the appropriat­e folders.

To use the Bootstrap framework, simply add the lines below into the head of the index.html file. <link rel="stylesheet” href="css/bootstrap.min.css”> <script src="js/bootstrap.min.js"> </script>

On to Page #1

Okay, so let’s look at www/index.html file and get down to work. If you click the code that says <div data-role="page” id="page1"> , you’ll see it turn yellow and the closing </div> tag will be yellow too.

It’s between these lines where we’ll add the code for Page 1. To be more precise, the div tag with the class ui-content is the coding zone.

So, let’s add one new block of text using Bootstrap classes. The code can go directly above the closing div tag for the ui-content class. It’s simply a Bootstrap row with one column, as follows: <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12">Text</div> </div>

If you’ve clicked through pages 1-3, you’ll notice page 1 has an image, Apache Cordova text and a button that says Device Is Ready. To make this simple, we’ll change the logo and text, and add an API to fetch Wordpress posts.

First, the logo. We can change the logo easily. It’s the file logo.png located in the www/img folder. You can right-click it from the NetBeans menu and select Properties to see the details like size and file size.

To change the image, you can paste it into the img folder or you can edit a transparen­t image with a tool like TheGimp and save it to that location.

If you want to change the CSS style for the image, you can open the index.css file and edit attributes for the .app class.

When styling an Android app, running tests in browser mode does have its perks. One advantage of using the browser to run the app is that you have access to browser tools like Firebug and Inspectors. Thus, you can modify the code with these tools until you have it perfected, then modify the code in the actual NetBeans editor.

Firebug, Inspect Element and Inspect are popular with front end developers for perfecting the website look because the browser changes the look as soon as any code edits are performed. Thus, saving and reloading isn’t required.

Now that the image is swapped, let’s change the ‘Apache Cordova Text’. An easy way to do so it to press Ctrl+F on your keyboard and type it in. The editor will then find its usages in the file.

The text string is easy to find: it’s located between the <h1></h1> tags. Simply add your new text and save it.

You can run the project to see updates whenever you want. On a personal note, when you have the console open in the NetBeans editor and located in the appropriat­e folder, you can easily run the command cordova run android to see new updates as desired.

Now that the text is saved, the next step in your approach is to use Ajax to retrieve all posts from a Wordpress website. Thus, open up www/js/index.js, and www/index.html and config.xml.

In order for your app to be able to use the REST api, you need to give it permission to do so. Thus, let’s start by installing the Cordova whitelist plugin. But first, make sure

that the command is in the root folder of the Android project before proceeding. cordova plugin add cordova-plugin-whitelist

After the plugin is installed, just do a little check to make sure that the allow-navigation tag allows the website, such as <allow-navigation href="*” />.

If you have a access origin tag, you can delete it or have it like <access origin="*” /> .

Besides that, you’ll need to alter the meta tag slightly to allow the app to access a particular website. So, the new meta tag is shown below with the addition of a web url. All that is added is the url of the website after s&apos;self&apos;

Don’t be intimidate­d by s&apos;self&apos; because it’s just the word self surrounded by html entities which in its entirety translates to self : content="default-src &apos;self&apos; http://growlode.com/ wp-json/wp/v2/posts

At this point, a simple ajax request in the index.js file gets the posts from the file and they are parsed with jQuery. The boxout ( previouspa­ge) shows the minimal boilerplat­e for handling Wordpress posts. The jQuery outputs a title with a link to the website. Now, let’s move on to page 2…

Turn to Page #2

With Page 2, the plan is to be able to take pictures and upload them to a remote website folder.

The first step is to add the Cordova camera plugin. cordova plugin add cordova-plugin-camera

After the install run its course, go back to index.js and index.html. In page 2, only a few lines of code are required to trigger the camera plugin to take photos and get photos. <button id = “cameraTake­Picture">TAKE PICTURE</ button> <img id="myImage"/> <button id = “cameraGetP­icture">GET PICTURE</button>

Asides from the html, you need to modify the index.js file to handle the click events.

Essentiall­y, you add event listeners for both click events, taking the picture and getting the picture. When you select Take Picture, your camera will pop up and you can take and save or discard an image.

If you discard and image, nothing happens, but if you save an image then it’ll be added into your source app and you’ll see it.

Meanwhile, if you select Get Picture then you’ll be able to choose an image on your camera and it’ll be inserted into page 2.

Transfer the photo

Let’s get into the details about sending the file to the remote server now. To make this an easy process, you can install a plugin called cordova-plugin-file-transfer: cordova plugin add cordova-plugin-file-transfer

Once that’s installed, you simply get back to your index.js file and add a little more code. This code will be added before the ending curly bracket } for the onSuccess() function that will run after you select an image from your camera.

The code is shown below. Have a look and then we’ll explain how it works. var win = function (r) {

alert("All Good!"); }

var fail = function (error) { alert("An error has occurred: Code = " + error.code); }

var options = new FileUpload­Options();

options.fileKey = “file”;

//fileURL= ‘data:image/jpeg;base64,‘+ imageData; fileURL= imageData; //options.fileName = fileURL.substr(fileURL.lastIndexO­f('/') + 1); var d = new Date().toISOStrin­g().slice(0,10); options.fileName =d + '.jpg’; options.mimeType = “image/jpeg”; options.chunkedMod­e = false; options.httpMethod = “POST”;

var params = {}; //params.username = “admin@admin.com”; //params.password = “adminpassw­ord”; params.username = window.localStora­ge. getItem("username"); params.password = window.localStora­ge. getItem("password"); options.params = params; var ft = new FileTransf­er(); ft.upload(fileURL, encodeURI("https://members.growlode. com/uploads-test.php"), win, fail, options);

The new FileUpload­Options() defines a set of options for using the plugin; such as file name, file mime type and http method such as POST and PUT.

Some parameters were created for username and password and validation on the server side.

The new FileTransf­er() object does the heavy lifting. The upload method sends the file to the remote server. Upon

success, the win() method runs and if not, the fail option. You’ll see a prompt at the end hopefully showing all went successful­ly.

Do note that this transmissi­on takes place with a username and password that is validated on the other server. You did not have to do that, but, it would be a requiremen­t for membership accounts and for the sake of avoiding a free for all of uploads.

In simple form, here is the code that is used to validate the uploads. To be more secure, you could add regex to ensure file extensions are adequate and mime types are valid and hashed passwords.

<?php if(isset($_POST['username']) && $_POST['username'] == ‘admin@admin.com’ && isset($_POST['password']) && $_ POST['password'] == ‘adminpassw­ord') { /* new_file can be any path ... */ $new_file = __DIR__ . ‘/uploads-test/’ . $_FILES['file'] ['name']; // echo $new_file; if (is_writable(dirname($new_file))) {

move_uploaded_file($_FILES['file']['tmp_name'], $new_file); } else {

throw new Exception('File upload failed: Directory is not writable.‘);

}

} ?>

Since this app requires authentica­tion on Page 2, Page 3 needs to be made just to accommodat­e that fact. Just a simple div tag with couple of buttons is added to your Page 3 code in the index.html file:

<div> User Name:<input type="text” id="username” /><br /> Password: <input type="text” id="password” /><br /> <button id="btnSave">Save Data</button><br /> <button id="btnGet">Get Data</button><br /> <div id="result"></div>

</div>

When Save Data is clicked, localstora­ge saves the username and password. Thus, those variables can be used to provide authentica­tion username and password when a files is transferre­d.

If you recall the part on Page 2 about authentica­tion, it uses a username and password generated from saving it from this form.

document.getElement­ById("btnSave").addEventLi­stener("clic k”,saveData, false); document.getElement­ById("btnGet"). addEventLi­stener("click”, getData, false); function saveData() {

var username = document. getElement­ById("username").value;

var password = document. getElement­ById("password").value;

window.localStora­ge.setItem("username”, username);

window.localStora­ge.setItem("password”, password);

alert("Your data is stored successful­y");

} function getData() {

var output = “Username is " + window.localStora­ge.getItem("username")

+ " and password is " + window.localStora­ge. getItem("password"); document.getElement­ById("result").innerHTML = output; }

Well, that’s it. Now you can make an app that get a list of posts from Wordpress websites. In addition you can take pictures and open images from your camera for which you can send to a remote server and validate the uploads on the server. Just remember that the folder for which you’ll send the files has write permission­s. Happy photo sharing!

 ??  ?? Save time and make realtime coding modificati­ons by running the app in a browser.
Save time and make realtime coding modificati­ons by running the app in a browser.
 ??  ?? When something goes awry, don’t panic. Running the ‘cordova requiremen­ts’ command can quickly pinpoint the problem.
When something goes awry, don’t panic. Running the ‘cordova requiremen­ts’ command can quickly pinpoint the problem.
 ??  ??
 ??  ?? NetBeans’ IDE editor offers dual action, coding the app and running the command line all in one window.
NetBeans’ IDE editor offers dual action, coding the app and running the command line all in one window.
 ??  ??
 ??  ??
 ??  ?? Coding can be test of patience at times and a nerve-shattering experience at others. But when you see a successful build you know you’re in the clear.
Coding can be test of patience at times and a nerve-shattering experience at others. But when you see a successful build you know you’re in the clear.

Newspapers in English

Newspapers from Australia