Creating first app with phonegap apache cordova and jquerymobile

It’s kindly obvious that if you are a web developer, it will be easier for you to entry into mobile development using web apps (html5 + JS) than native code.
I’m not writing this post to let you figure out all the capabilities and possibilities that web apps gives you instead of native apps, but for me there are. And basing my decision on this I would like to share my code of one of my first test projects/snippets using (in this case) Android, jQuerymobile and Apache Cordova / Phonegap (both names Cordova and Phonegap are used along the post to reference the same).

All the cited and detailed code below can be forked there:
https://github.com/llissssss/wp-feedreader-droidgap

and the working example to install to your phone here:
https://github.com/llissssss/wp-feedreader-droidgap/raw/master/bin/Albert%20Casadessus%20feed-reader.apk

The idea is to create a web app which requests all the posts of a wordpress site, and keep them in local storage, providing readability even when you are offline, and to sync with the site and get new posts when necessary.

What do I need to start?

Create project

Then create a project, with one empty activity. Then, edit your MainActivity.java to look like:

package com.albertcasadessus.albert.casadessus.feed_reader;
 
import android.os.Bundle;
import org.apache.cordova.DroidGap;
import android.app.Activity;
import android.view.Menu;
 
public class MainActivity extends DroidGap {
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
 
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

In /assets/www/ you should create your index.html file.
At this point, you don’t need to code java or change android parameters anymore, well I’m mistaken, you need to modify your AndroidMAnifest.xml to add the permissions we’ll request to use on our app:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />   
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />   
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />

Not all of them are necessary. For this project we just need to check the internet connection, access to read and write local storage, and notifications.

The code.

All the needed code is linked git. As I said before, you can also fork the project on github.

The code (HTML)

The HTML has no secrets. In <head> I just referenced the necessary files. Body is created using jquerymobile because I didn’t want to spend time creating the visual interface for a test.

https://github.com/llissssss/wp-feedreader-droidgap/blob/master/assets/www/index.html

The code (JS)

First line is the one which fires the applications. When phonegap is ready to access phone utils, is launched.

document.addEventListener("deviceready", onDeviceReady, false);

On that function, I open the database to work with. And I load the data stored in local storage with getJsonDB(), and I try to get data from the wordpress site calling getJsonFromWeb(), using sqlite and key/value pairs.

getJsonDB() , creates the table if not exists (first launch) and tries to retrive the posts stored in local. Calling processJsonDB() checks if there’s local data, if not notificates the user using native phone notifications, but If there’s, generates the page content (see generatePageFromJson())

In parallel, via ajax, I request the posts from the wp site. If request fails and there’s no local data, I show a error, but if not, local posts are displayed.
If everything went okay, I update the local data via updateData() and the page, well the post lists is re-generated with new data calling the previous function generatePageFromJson()

Have a look at the code and everything is going to be clearer for you.

https://github.com/llissssss/wp-feedreader-droidgap/blob/master/assets/www/js/funcions.js

Easy isn’t it? I guess you may be thinking why I not compare the posts date in order to decide if there have been changed, but that’s not the aim of project, so please just note about the use of phone utilities such as notifications, checking internet connectivity, and local storage and how easy is to create just once the logic and the interface and being able to use it in all platforms.

 

To try this example, you can install the app on your phone:

https://github.com/llissssss/wp-feedreader-droidgap/raw/master/bin/Albert%20Casadessus%20feed-reader.apk

 

Read More

5 Things to keep in mind while planning your own project.

Those days I’m deeply thinking about some projects that I’ve got in mind for a while. Nowadays, after finishing my diploma and having a (little) more time to carry on my own projects, I realised of some things that it’s important to keep in mind when you are trying to develop your own project. Mainly, these things are kind of obvious, but I think are important to always have it in consideration.

  1. Pay full attention to your daily life.
    It is important to be always in alert about all the situations that will come across your normal life. Maybe it couldn’t look important for you to read those lines, but if you are always aware (and awake!), you are going to discover things that will produce a real brain-storming in your head.
     
  2. Carry always a (paper) notebook.
    Or your laptop, or a tablet, or whatever thing you use to write your own ideas. Because of the previous point, you are not going to predict where in the world your ideas will come to you, and you should be ready to note it (don’t expect to be in your workplace trying to discover some brilliant ideas, usually this will not happen).
     
  3. Share your ideas to confident people.
    Sharing your ideas to third parties, will cause that you will have to explain your ideas aloud and even before you finish, you will realise about your own mistakes or things to improve in your project. I say confident people because they will have enough confidence to “criticise”.
     
  4. Be open-minded.
    And of course, be always open-minded about what third parties will say about your thoughts: you’ll learn a lot and who knows, maybe you’ll get greater and brilliant ideas!
     
  5. Learn how to make it real.
    And not just in a technologic way! Even it’s more important to have “vision of company”, learn how you will earn money if you make it real, how your business will work, to which target of people your project is focused… and a huge list! Do not worry to much in how you will develop it in a technical vision, that’s not the biggest deal and probably you’re trained on it, so it’s very important to have a deployment plan.
     

By the way I’ve to say that for obvious they may seem, I have been impressed of how they true are, so keep them in mind: it’s not a lot of information that you couldn’t retain!

Read More

Reading files with PHP: “auto detect line endings”

With this PHP code:

<?php
$fp = @fopen("file.txt", "r");
if ($fp)
{
	$i = 1;
	while (($line = fgets($fp, 4096)) !== false)
	{
		echo "Line ".$i.": ".$line;
		$i++;
	}
}
?>

And this file.txt content:

aaaaa
bbbbb
ccccc
ddddd

You expect an output like:

Line 1: aaaaa
Line 2: bbbbb
Line 3: ccccc
Line 4: ddddd

A problem appears when you read a file created in a Mac environment (eg, \r instead of \n ). Then you could get something like:

Line 1: aaaaa bbbbb
Line 2: ccccc
Line 3: ddddd

To avoid that and always get a correct (and an expected!) performance, just add this line in the beginning of your code:

ini_set("auto_detect_line_endings", true);

Read More

Geolocation API with HTML5

Geolocation API and a browser supporting HTML5 location feature, may help you to know geolocation of a visitor (not so much accurate, cause it doesn’t use GPS to get location).
How? Let’s take a look to a simple code:

function GeoHtml5()
{
	if (navigator.geolocation)
        navigator.geolocation.getCurrentPosition(onGetPosition,onErrorPosition);
	else
        alert("geo not supported");
}
 
function onGetPosition(geolocation)
{
    var latitude = geolocation.coords.latitude;
    var longitude = geolocation.coords.longitude;
    alert("Your lat: " + latitude + "\nYour long: " +  longitude);
}
function onErrorPosition()
{
    alert("Error on get position");
}

First function, detects if browser supports this feature. Second one is triggered when getting location is OK, second one when it’s not. I’m not going to explain inline code, because it’s very intuitive and simple.

Here is the code running.

If W3C and browser “companies” improves it, it could reduce a little bit more differences with mobile’s web-apps and native apps.

For more information, visit W3c’s Geolocation API site.

Read More

How and why to create a “child theme” in WordPress

Child themes are those which inherit styles and functionalities from another parent theme.

Why use child themes?
One of multiple utilities reside in change ,for example, only the styles/appearance without creating a new theme (because a child theme, just require a style.css file). For example, if you want to change colorset of your current theme and you edit their style.css, everything will be ok… until you update your theme and you will lose all your changes.

How to do that?
Is simple as just create one folder in your /wp-content/themes/ , just as another wp theme. Then, just copy (eg.) parent theme style.css, and add this at the beggining:

/*
Theme Name:     Responsive personalitzat
Description:    Child theme for responsive theme
Author:         Albert Casadessús
Author URI:     http://www.albertcasadessus.com/
Template:       responsive
Version:        0.1.0
*/

Where Template must be the name of the parent theme folder (case sensitive!). Above there’s style.css of my child theme to change a bit the responsive theme I use.

So in this example, my folder struct will be:
/wp-content/themes/responsive_child
/wp-content/themes/responsive_child/style.css
(and if you want to modify another files, just put in the folder and think about the header above)
/wp-content/themes/responsive/
/wp-content/themes/responsive/(with all the files of the theme)

Read More

Get web browser preferred language with PHP $_SERVER variables HTTP_ACCEPT_LANGUAGE

HTTP Language headers.
In php the way to get the language information sent by browser is with server reserved variables.

1
2
3
<?php
echo $_SERVER['HTTP_ACCEPT_LANGUAGE']);
?>

Which output (in my browsers):

  • ca,en-us;q=0.7,en;q=0.3 in Mozilla Firefox 13.0.1
  • es-ES in Internet Explorer 9 64b
  • ca-ES,ca;q=0.8 in Google Chrome 20.0

The “q-value” (when it’s shown in a value range between 0-1) indicates the percent that the browser prefer this language. If it’s not provided, we asume is 1 (maximum).

How to get the preferred language?
Here’s a simple function I’ve coded to get the preferred language according q-value in ISO 639-1 format:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
function GetLanguageCodeISO6391()
{
	$hi_code = "";
	$hi_quof = 0;
	$langs = explode(",",$_SERVER['HTTP_ACCEPT_LANGUAGE']);
	foreach($langs as $lang)
	{
		list($codelang,$quoficient) = explode(";",$lang);
		if($quoficient == NULL) $quoficient = 1;
		if($quoficient > $hi_quof)
		{
			$hi_code = substr($codelang,0,2);
			$hi_quof = $quoficient;
		}
	}
	return $hi_code;
}
 
echo "Your browser preferred language is: ".GetLanguageCodeISO6391();
?>

To check what will output in your browser, go to this demo.

 

Read More

Redirect a domain to another file domain keeping web browser URL (htaccess)

Situation:
You have a site (eg. www.mysite.com) and a page of this site dedicated to photography (eg. www.mysite.com/photography.html) . For some reason you buy another domain (eg. www.photosite.com) and want to render your photography.html page below this new domain.

Solution:
Use a htaccess file running Apache server to solve that. How?

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^$ photography.html [L]
RewriteRule ^(.*)$ http://www.photosite.com/$1 [P]

And upload it to you new domain renaming the name to .htaccess .

Explanation:

  1. First rule will redirect www.photosite.com to www.photosite.com/photography.html
  2. Second one will “render” every www.mysite.com/any-site-page.html under domain www.photosite.com, and keeping this url domain even navigating between different pages (that’s why there’s a [P], standing for Proxy).

Hope you you find it useful.

Read More

Warning: Cannot modify header information – headers already sent

Sometimes programming with PHP and trying to redirect pages with header(“location:”.$site); , it’s possible to get the following warning:
Warning: Cannot modify header information – headers already sent
This may occur for one of those reasons:

  • Start the file with (or including a file which starts with):
    1
    2
    3
    
    <?php
     
    // the code starts here, above there's a whitespace
  • Having previously in the script (or including a file which have it) whitespaces :
    1
    2
    3
    4
    5
    6
    7
    
    <?php
    // some example code...
    ?>
     
    <?php
    // more example code lines...
    ?>
  • Print or echo of a variable or text before sending headers.
  • HTML code before sending headers.
  • A mix of the above reasons…

Sometimes, depending on PHP version, everything seems to be okay but when you run the script, it doesn’t work. Let’s see an example:

Warning: Cannot modify header information – headers already sent by (output started at /full/route/to/file/which/previously/has/sent/headers/included.php:xx) in /full/route/which/has/sending/header/script.php on line xx

In script.php there is eg. header(“location:script2.php); and apparently headers has sent before in included.php.

In included.php:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
// code
if ($lang== "es")
{
	include("spanish.inc.php");
}
elseif ($lang== "en")
{
	include("english.inc.php");
}
// more code
?>

Imagine your error is on include(“spanish.inc.php”) and obviously the included file is ok (eg. empty). Then why there’s an error? Some php versions or apache/iis configurations, make an include (or require, require_once, …) works as an output buffer. To avoid that, just wrap the “conflictive” code with:

ob_start();
// code which have include or require, etc.
ob_clean();

So, finally In included.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// code
ob_start();
if ($lang== "es")
{
	include("spanish.inc.php");
}
elseif ($lang== "en")
{
	include("english.inc.php");
}
ob_clean();
// more code
?>

 

More information about those php functions here and here.

Read More

Date, time and other web selectors with mobile appearance.

Sometimes, it may be interessant (and perhaps easier and faster) to develop web-apps instead of native mobile apps. But the main issue is about the appearance problem. Nowadays, all those problems are minimized with html5, css3 and (eg. jQuery) JS libraries.

Today I’m not presenting any own source code, I just share a jQuery plugin that I found on web, to avoid appeareance problems on web-apps (at least in selectors). Their site is Mobiscroll, and you can find some sampleson their demo page . With that plugin, you can present simple date (or other selector) input forms, looks like:


Android system.


iOS system.


Or even HTC Sense.

And of course, as always with jQuery usage ease and MIT license.

Source: Mobiscroll developer by Acid Media.

Read More

Differences on DOM javascript setAttribute method between IE & other browsers.

Because a project of my job, I’m working in a dinamic creation of a webpage using Javascript to handle DOM.

Today I realised, that my original code (according to W3C) does not work properly with any version of IE, so for example, originally to create a input element I did:

1
2
3
4
5
6
7
8
9
// code
INPUTELM = document.createElement('input');
INPUTELM.setAttribute('name', 'codes[]');
INPUTELM.setAttribute('type', 'text');
INPUTELM.onkeyup = function(){ChangeSelectArticleByValue(this.value,'article' + (num_linies-1))}
INPUTELM.setAttribute('class', 'boxes');
INPUTELM.setAttribute('id', 'code' + (num_linies-1));
INPUTELM.setAttribute('tabindex',tabIndex);
// more code

The class attribute was not set, neither tabindex. After searching for a while I found that I might use (new methods below each one, lines 7 and 10)

1
2
3
4
5
6
7
8
9
10
// code
INPUTELM = document.createElement('input');
INPUTELM.setAttribute('name', 'codes[]');
INPUTELM.setAttribute('type', 'text');
INPUTELM.onkeyup = function(){ChangeSelectArticleByValue(this.value,'article' + (num_linies-1))}
INPUTELM.setAttribute('class', 'boxes');
INPUTELM.className= 'boxes'; // ADDED LINE
INPUTELM.setAttribute('id', 'code' + (num_linies-1));
INPUTELM.setAttribute('tabindex',tabIndex);
INPUTELM.tabIndex = tabIndex; // ADDED LINE

So mainly it seems that we might:

  • Use setAttribute for all most browsers, and the property for IE. Each browser will execute their code and avoid the other one.
  • To set class, use className because “class” is a JS reserved word.
  • Note uppercase in two or more words attributes.

I will edit this post if I deep on this.

 

Read More