Showing posts with label Phonegap. Show all posts
Showing posts with label Phonegap. Show all posts

Tuesday, 18 September 2012

Use XML to reduce access time - Android

I was working with language translation in phone gap. In that case I was in need of 120 labels for translation. Out of 120, 60 are English and remaining are of other language. I was inserting all values in database ones on the very first start of application, because of that it was taking much time to start for first time. After that when I was using those labels in my app, there was much delay. Means all elements on page like button, text boxes were coming first and then labels. Because of that buttons were remaining empty first and then after some time text was appearing on that.

In order to solve this problem I am using XML database for fast access. Now I created simple XML file as given below,

english_translation_test.xml

<xml>
    <lbl1>Label - 1</ lbl1 >
    <lbl2>Label - 2</ lbl2 >
    <lbl3>Label - 3</ lbl3 >
</xml>

In this way I designed simple XML file, one for English and another for different language. I placed this file at place www => xml => english_translation_test.xml
In order to access this file I am using following code. In this code remember one thing that path must be relative to www folder. Path is in red color.


$.get('xml/english_translation_test.xml ', function(rawXml) {
getPlainXml(rawXml);
});

function  getPlainXml(xml)
{
        $('#label_1').html($(xml).find("lbl1").text());

$('#label_2').html($(xml).find("lbl2").text());

$('#label_3').html($(xml).find("lbl3").text());
}

Now in this case if language is different then use another language that's it. And you will get fast access to all your labels. You may need this process while code optimization and performance issues.

Background jerk problem because of keypad - Phone gap

In our phone gap application many times we encounter the problem of background. In this problem background image moves up when soft keypad comes up. In some cases all elements on screen like buttons, text fields moves up more than necessary.
In order to keep your screen and background fix you can use following solutions,

1. For keeping your elements on screen fix, you can use "overflow: hidden;" in your css for that element. You can apply this css to the div in which all elements are present.

2. By using above solution elements on screen will become fix but background image may move up. In order to fix background as well as elements you have to add just one line code to your activity tag present in manifest file. 

Code:
 <activity
            android:windowSoftInputMode="adjustPan"
            android:name=".Test"
            android:label="Test"
            android:configChanges="orientation|keyboardHidden" >
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
 </activity>
Here you have to add line in red color. You can try different options of that property.

Tuesday, 4 September 2012

Database problem in phonegap

In phone gap many times you can see that database operations are not working properly. In many cases I found that we are redirecting to some other page just after the database operation. Here is block of code,

insertData(data1, data2);
window.location = "abc.html";

And here is insertData function,


function insertDatas(data1, data2) {
        //Here I am assuming db is initialized properly.
db.transaction(insertHere, errorDataTable, successDataTable);
    function insertHere(tx) {
        var query = "insert into dataTable values('" + data1 + "','" + data2 + "')";
        tx.executeSql(query);
    }
    function errorDataTable(err){
          alert("Error : " + err);
    }
    function successDataTable() {
          alert("Success");
    }
}

Now here sometimes it may happen that, values are going to database. At place you may have update query In case of update values may not updated in database.

In order to fix this problem safe way to code in phonegap is to commit database after your operations. Here is code block with commit statement which is doing the same functionality as above but safely,

insertData(data1, data2);
//After this statement instead of redirecting call commit,

db.transaction(commit, errorCommit, successCommit);
 function commit(tx){
        tx.executeSql("COMMIT",[], commited, errorCommit);
 }
         
 function commited() {
        console.log('commit successful..');
        window.location = "abc.html";
}
         
function errorCommit() {
}
function successCommit() {
         console.log('commit successful.. redirecting');
        window.location = "abc.html"
}

So in phonegap always it is safe to commit your database. I have faced this problem with update statement.

Wednesday, 29 August 2012

Writing Plugins For Phonegap In Android


Note: Here it is assumed that you have properly running Phone gap project.
Writing plugins is very easy for android in phonegap. Here are simple four steps to write plugins.


1.  Create TestingPlugin.java class in src folder of your eclipse project.
Replace that file with following code,
Code:
package src.com.testing; 
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
public class TestingPlugin extends Plugin { 
      @Override
      public PluginResult execute(String action, JSONArray data, String callbackId) {
            try {
                  return new PluginResult(PluginResult.Status.OK, "Process successful");
            } catch(Exception e) {
                  return new PluginResult(PluginResult.Status.ERROR, "Process fail");
            }
      }

} 
Remember one thing that, method from plugin class can return PluginResult only.


2. Now in your www folder create one html file and use following code,
Code:
<!DOCTYPE HTML>
<html>
<head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="stylesheets/jquery.mobile-1.1.0.min.css" />
      <script src="scripts/jquery-1.7.1.min.js"></script>
      <script src="scripts/TestingPlugin.js"></script>
      <script src="scripts/jquery.mobile-1.1.0.min.js"></script>
      <script type="text/javascript" charset="utf-8" src="scripts/cordova-2.0.0.js"></script>
      <script type="text/javascript">
      function onBodyLoad()
      {          
            document.addEventListener("deviceready", onDeviceReady, false);
      }
      function onDeviceReady() {
            navigator.notification.alert("Testing")
      }
    function callNativePlugin( returnSuccess ) {
        TestingPlugin.callNativeFunction( success, fail, returnSuccess );
    }
    function success (result) {
       alert("SUCCESS: \r\n"+result );
    }
    function fail (error) {
       alert("ERROR: \r\n"+error );
    }
    </script>
    </head>
      <body onload="onBodyLoad()">
            <h1>Testing</h1> 
            <button onclick="callNativePlugin('Your_parameters');">Invoke plugin</button>
      </body>
</html>

Here include all necessary scripts carefully. Important script is highlighted here. It is necessary for calling plugin function.


3. Now in "www -> scripts" folder create TestingPlugin.js file and use following code.
Code:
var TestingPlugin = {
    callNativeFunction: function (success, fail, resultType) {
      return cordova.exec(success, fail, "src.com.testingplugin.TestingPlugin", "nativeAction", [resultType]);
    }
};



4.  Now open "res -> xml -> plugins.xml" file and past following line of code under <plugins></plugins> tag,
Code:
<plugin name=”src.com.testingplugin.TestingPlugin” value=” src.com.testingplugin.TestingPlugin”/>


5. And here you are ready to go. Here for every facility you have to write one class. 

Enjoy plugins....