An­droid apps

The ever-in­trepid Kent Elchuk takes you on an­other gold-seek­ing ride along Cor­dova Al­ley for build­ing that next An­droid app. Hold on tight!

Linux Format - - CONTENTS - Kent Elchuk is an ex­pe­ri­enced web de­vel­oper who’s built many web ap­pli­ca­tions for high schools, col­leges, small busi­nesses and per­sonal plea­sure.

Kent Elchuk is on a gold-seek­ing ride down Cor­dova Al­ley for build­ing that next An­droid app.

Back in is­sue LXF225, we cov­ered how to set up Linux and build very ba­sic Cor­dova 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 but­ton.

By the time you get to the end of this short ar­ti­cle, you’ll know how to build an An­droid app us­ing Cor­dova that will be able to do a range of tasks: from us­ing the Word­press REST api to return json strings and get­ting images from your cam­era and send­ing them to a re­mote server.

The first step to build­ing an app is to use the cor­dova cre­ate com­mand. If you have al­ready built a sim­ple Cor­dova app in the past, or have read my pre­vi­ous ar­ti­cle about Cor­dova apps and fol­lowed in­struc­tions, you should be good to go. If not, don’t worry – visit https://cor­ docs/en/lat­est/guide/cli/ to find out how to set your ma­chine up. In this tu­to­rial, there’ll be ref­er­ences made to the NetBeans ed­i­tor. You can down­load it at https://netbeans. org/down­loads/.

So, be­fore start­ing this tu­to­rial, you should be able to cre­ate a sim­ple An­droid app with your sys­tem and edit it with NetBeans. Mov­ing on from the var­i­ous ba­sic setup de­tails, let’s go into more de­tails about build­ing an app with mul­ti­ple pages. Note that this pro­ce­dure will be cov­ered from be­gin­ning to end, in­clud­ing the ini­tial in­stal­la­tion from the com­mand line.

The app you’re about to build will have sev­eral pages that will do var­i­ous tasks. For ex­am­ple, one page will be a REST api that lists all the posts from a Word­press site. The ti­tles with be link­able and you can open them up as you see fit.

So, let’s start by in­stalling a Jquery mo­bile app via the com­mand line with a list view for our sev­eral page.

The first step is to add the cor­dova-jquery mod­ule: sudo npm in­stall -g cor­dova-jquery

Af­ter that, you use the cor­dovacre­ate com­mand fol­lowed by the folder name you want for the project, fol­lowed by a few more com­mands as demon­strated below. cor­dova cre­ate jquery_­mo­bile cd jquery_­mo­bile cor­dova-jquery

When prompted “Would you like to add jQuery mo­bile…” type Y and hit En­ter. Af­ter that, you’ll be asked what to do. Se­lect ‘ap­plyTem­plate’. Af­ter that, choose listView. Then, type Y to keep the code.

That’s it. Now you can add the An­droid plat­form, build it and test it in your An­droid phone. cor­dova plat­form add an­droid cor­dova build cor­dova run an­droid

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

If you take a brief look, you can see that Jquery mo­bile uses data-role=”page” and in­di­vid­ual page ids for each page. In the case of these three pages, the in­di­vid­ual page ids for each page are page1, page2 and page3.

Now, you can eas­ily make a clean-look­ing app. How­ever, you can go a step fur­ther and add a CSS frame­work such as

Boot­strap for your cod­ing en­deav­our. Ad­ding Boot­strap is just a mat­ter of ad­ding boot­srap.min.css to the www/css folder and boot­strap.min.js to the www/js folder.

An­other way to get Boot­strap is to make a Cor­dova app with NetBeans with the Twit­ter Boot­strap tem­plate and copy the files from the css and js fold­ers. You sim­ply click each file while hold­ing down the Ctrl key. Then right-click copy and paste them to the ap­pro­pri­ate fold­ers.

To use the Boot­strap frame­work, sim­ply add the lines below into the head of the in­dex.html file. <link rel="stylesheet” href="css/boot­strap.min.css”> <script src="js/boot­strap.min.js"> </script>

On to Page #1

Okay, so let’s look at www/in­dex.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 yel­low and the clos­ing </div> tag will be yel­low too.

It’s be­tween these lines where we’ll add the code for Page 1. To be more pre­cise, the div tag with the class ui-con­tent is the cod­ing zone.

So, let’s add one new block of text us­ing Boot­strap classes. The code can go di­rectly above the clos­ing div tag for the ui-con­tent class. It’s sim­ply a Boot­strap row with one col­umn, as fol­lows: <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 no­tice page 1 has an im­age, Apache Cor­dova text and a but­ton that says De­vice Is Ready. To make this sim­ple, we’ll change the logo and text, and add an API to fetch Word­press posts.

First, the logo. We can change the logo eas­ily. It’s the file logo.png lo­cated in the www/img folder. You can right-click it from the NetBeans menu and se­lect Prop­er­ties to see the de­tails like size and file size.

To change the im­age, you can paste it into the img folder or you can edit a trans­par­ent im­age with a tool like TheGimp and save it to that lo­ca­tion.

If you want to change the CSS style for the im­age, you can open the in­dex.css file and edit at­tributes for the .app class.

When styling an An­droid app, run­ning tests in browser mode does have its perks. One ad­van­tage of us­ing the browser to run the app is that you have ac­cess to browser tools like Fire­bug and In­spec­tors. Thus, you can mod­ify the code with these tools un­til you have it per­fected, then mod­ify the code in the ac­tual NetBeans ed­i­tor.

Fire­bug, In­spect El­e­ment and In­spect are pop­u­lar with front end de­vel­op­ers for per­fect­ing the web­site look be­cause the browser changes the look as soon as any code ed­its are per­formed. Thus, sav­ing and reload­ing isn’t re­quired.

Now that the im­age is swapped, let’s change the ‘Apache Cor­dova Text’. An easy way to do so it to press Ctrl+F on your key­board and type it in. The ed­i­tor will then find its us­ages in the file.

The text string is easy to find: it’s lo­cated be­tween the <h1></h1> tags. Sim­ply add your new text and save it.

You can run the project to see updates when­ever you want. On a per­sonal note, when you have the con­sole open in the NetBeans ed­i­tor and lo­cated in the ap­pro­pri­ate folder, you can eas­ily run the com­mand cor­dova run an­droid to see new updates as de­sired.

Now that the text is saved, the next step in your ap­proach is to use Ajax to re­trieve all posts from a Word­press web­site. Thus, open up www/js/in­dex.js, and www/in­dex.html and con­fig.xml.

In order for your app to be able to use the REST api, you need to give it per­mis­sion to do so. Thus, let’s start by in­stalling the Cor­dova whitelist plugin. But first, make sure

that the com­mand is in the root folder of the An­droid project be­fore pro­ceed­ing. cor­dova plugin add cor­dova-plugin-whitelist

Af­ter the plugin is in­stalled, just do a lit­tle check to make sure that the al­low-nav­i­ga­tion tag al­lows the web­site, such as <al­low-nav­i­ga­tion href="*” />.

If you have a ac­cess ori­gin tag, you can delete it or have it like <ac­cess ori­gin="*” /> .

Be­sides that, you’ll need to al­ter the meta tag slightly to al­low the app to ac­cess a par­tic­u­lar web­site. So, the new meta tag is shown below with the ad­di­tion of a web url. All that is added is the url of the web­site af­ter s&apos;self&apos;

Don’t be in­tim­i­dated by s&apos;self&apos; be­cause it’s just the word self sur­rounded by html en­ti­ties which in its en­tirety trans­lates to self : con­tent="de­fault-src &apos;self&apos; wp-json/wp/v2/posts

At this point, a sim­ple ajax re­quest in the in­dex.js file gets the posts from the file and they are parsed with jQuery. The box­out ( pre­vi­ous­page) shows the min­i­mal boil­er­plate for han­dling Word­press posts. The jQuery out­puts a ti­tle with a link to the web­site. Now, let’s move on to page 2…

Turn to Page #2

With Page 2, the plan is to be able to take pic­tures and up­load them to a re­mote web­site folder.

The first step is to add the Cor­dova cam­era plugin. cor­dova plugin add cor­dova-plugin-cam­era

Af­ter the in­stall run its course, go back to in­dex.js and in­dex.html. In page 2, only a few lines of code are re­quired to trig­ger the cam­era plugin to take pho­tos and get pho­tos. <but­ton id = “cam­er­aTakePic­ture">TAKE PIC­TURE</ but­ton> <img id="myI­mage"/> <but­ton id = “cam­er­aGetPic­ture">GET PIC­TURE</but­ton>

Asides from the html, you need to mod­ify the in­dex.js file to han­dle the click events.

Es­sen­tially, you add event lis­ten­ers for both click events, tak­ing the pic­ture and get­ting the pic­ture. When you se­lect Take Pic­ture, your cam­era will pop up and you can take and save or dis­card an im­age.

If you dis­card and im­age, noth­ing hap­pens, but if you save an im­age then it’ll be added into your source app and you’ll see it.

Mean­while, if you se­lect Get Pic­ture then you’ll be able to choose an im­age on your cam­era and it’ll be in­serted into page 2.

Trans­fer the photo

Let’s get into the de­tails about send­ing the file to the re­mote server now. To make this an easy process, you can in­stall a plugin called cor­dova-plugin-file-trans­fer: cor­dova plugin add cor­dova-plugin-file-trans­fer

Once that’s in­stalled, you sim­ply get back to your in­dex.js file and add a lit­tle more code. This code will be added be­fore the end­ing curly bracket } for the onSuc­cess() func­tion that will run af­ter you se­lect an im­age from your cam­era.

The code is shown below. Have a look and then we’ll ex­plain how it works. var win = func­tion (r) {

alert("All Good!"); }

var fail = func­tion (er­ror) { alert("An er­ror has oc­curred: Code = " + er­ror.code); }

var op­tions = new FileU­pload­Op­tions();

op­tions.fileKey = “file”;

//fileURL= ‘data:im­age/jpeg;base64,‘+ im­ageData; fileURL= im­ageData; //op­tions.fileName = fileURL.sub­str(fileURL.lastIn­dexOf('/') + 1); var d = new Date().toISOString().slice(0,10); op­tions.fileName =d + '.jpg’; op­tions.mimeType = “im­age/jpeg”; op­tions.chun­kedMode = false; op­tions.httpMethod = “POST”;

var params = {}; //params.user­name = “ad­min@ad­”; //params.password = “ad­min­pass­word”; params.user­name = win­dow.lo­calS­tor­age. getItem("user­name"); params.password = win­dow.lo­calS­tor­age. getItem("password"); op­tions.params = params; var ft = new FileTrans­fer(); ft.up­load(fileURL, en­codeURI("https://mem­bers.growlode. com/up­loads-test.php"), win, fail, op­tions);

The new FileU­pload­Op­tions() de­fines a set of op­tions for us­ing the plugin; such as file name, file mime type and http method such as POST and PUT.

Some pa­ram­e­ters were cre­ated for user­name and password and val­i­da­tion on the server side.

The new FileTrans­fer() ob­ject does the heavy lift­ing. The up­load method sends the file to the re­mote server. Upon

suc­cess, the win() method runs and if not, the fail op­tion. You’ll see a prompt at the end hope­fully show­ing all went suc­cess­fully.

Do note that this trans­mis­sion takes place with a user­name and password that is val­i­dated on the other server. You did not have to do that, but, it would be a re­quire­ment for membership ac­counts and for the sake of avoid­ing a free for all of up­loads.

In sim­ple form, here is the code that is used to val­i­date the up­loads. To be more se­cure, you could add regex to en­sure file ex­ten­sions are ad­e­quate and mime types are valid and hashed pass­words.

<?php if(is­set($_POST['user­name']) && $_POST['user­name'] == ‘ad­min@ad­’ && is­set($_POST['password']) && $_ POST['password'] == ‘ad­min­pass­word') { /* new_­file can be any path ... */ $new_­file = __DIR__ . ‘/up­loads-test/’ . $_FILES['file'] ['name']; // echo $new_­file; if (is_writable(dirname($new_­file))) {

move_u­pload­ed_­file($_FILES['file']['tm­p_­name'], $new_­file); } else {

throw new Ex­cep­tion('File up­load failed: Di­rec­tory is not writable.‘);


} ?>

Since this app re­quires au­then­ti­ca­tion on Page 2, Page 3 needs to be made just to ac­com­mo­date that fact. Just a sim­ple div tag with cou­ple of but­tons is added to your Page 3 code in the in­dex.html file:

<div> User Name:<in­put type="text” id="user­name” /><br /> Password: <in­put type="text” id="password” /><br /> <but­ton id="bt­nSave">Save Data</but­ton><br /> <but­ton id="bt­nGet">Get Data</but­ton><br /> <div id="re­sult"></div>


When Save Data is clicked, lo­cals­tor­age saves the user­name and password. Thus, those vari­ables can be used to pro­vide au­then­ti­ca­tion user­name and password when a files is trans­ferred.

If you re­call the part on Page 2 about au­then­ti­ca­tion, it uses a user­name and password gen­er­ated from sav­ing it from this form.

doc­u­ment.getEle­men­tById("bt­nSave").ad­dEven­tLis­tener("clic k”,saveData, false); doc­u­ment.getEle­men­tById("bt­nGet"). ad­dEven­tLis­tener("click”, getData, false); func­tion saveData() {

var user­name = doc­u­ment. getEle­men­tById("user­name").value;

var password = doc­u­ment. getEle­men­tById("password").value;

win­dow.lo­calS­tor­age.setItem("user­name”, user­name);

win­dow.lo­calS­tor­age.setItem("password”, password);

alert("Your data is stored suc­cess­fuly");

} func­tion getData() {

var out­put = “User­name is " + win­dow.lo­calS­tor­age.getItem("user­name")

+ " and password is " + win­dow.lo­calS­tor­age. getItem("password"); doc­u­ment.getEle­men­tById("re­sult").in­nerHTML = out­put; }

Well, that’s it. Now you can make an app that get a list of posts from Word­press web­sites. In ad­di­tion you can take pic­tures and open images from your cam­era for which you can send to a re­mote server and val­i­date the up­loads on the server. Just re­mem­ber that the folder for which you’ll send the files has write per­mis­sions. Happy photo shar­ing!

Save time and make re­al­time cod­ing mod­i­fi­ca­tions by run­ning the app in a browser.

When some­thing goes awry, don’t panic. Run­ning the ‘cor­dova re­quire­ments’ com­mand can quickly pin­point the prob­lem.

NetBeans’ IDE ed­i­tor of­fers dual ac­tion, cod­ing the app and run­ning the com­mand line all in one win­dow.

Cod­ing can be test of pa­tience at times and a nerve-shat­ter­ing ex­pe­ri­ence at oth­ers. But when you see a suc­cess­ful build you know you’re in the clear.

Newspapers in English

Newspapers from Australia

© PressReader. All rights reserved.