This is a migrated thread and some comments may be shown as answers.

Everlive cloud to update local .json file

6 Answers 183 Views
General Discussion
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Igor
Top achievements
Rank 1
Igor asked on 05 Apr 2014, 07:31 PM
Hi I am new to telerik backend services and I have a question.

I know it is possible to display the data in the backend on the hybrid mobile app with:

    <script>
    var el = new Everlive('api-key);
    var data = el.data('type-name);
    data.get()
    .then(function(data){
        alert(JSON.stringify(data));
    },
    function(error){
        alert(JSON.stringify(error));
    });
    </script>

However, I would like to use everlive to get and overwrite the local JSON file like in the MOBILE HYBRID APP sample data/weather.json

[
    {
        "day": "Monday",
            "Size": [
                            "Small",
                            "Medium",
                            "Large"
                           ]                  
        "image": "shower"
    }    
]

Can you please help me with a code sample to write var data to the local folder data/data.json?

I would like to "update" the app when the device is online, but there is a gap in the samples.

Everlive Type contents:
string day, List<string> size, image: file

Can you help me bridge the gap in this code to write and replace the local JSON file on "online" event? 

I appreciate your help




6 Answers, 1 is accepted

Sort by
0
Anton Dobrev
Telerik team
answered on 08 Apr 2014, 03:46 PM

Hi Igor,

Unfortunately, we do not have a sample app illustrating offline synchronization of data with Telerik Backend Services. A simple, but relevant sample for caching data from Backend Services is described in this blog post.

In regard to the offline data storage on the device, a recommended approach would be to use local storage or WebSQL (limited to 5 MB of data), or the integrated in AppBuilder SQLite plugin. Reading and writing a JSON data from/to a file will be time and resource consuming.

Here are some resources:
- Blog post that contains some highlights on offline syncing.
- Another comprehensive blog posts:  blog post 1 and blog post 2.
- A Kendo UI DataSource that uses WebSQL for local data persistence - here is a demo with full CRUD example.
- An AppBuilder  SQLite demo.

In AppBuilder, you can use the Cordova online/offline events of the device to trigger your custom logic and download/upload the appropriate data. There is a sample app for the device events. The AppBuilder team has a very informative series of blog posts on this topic.

We consider that there might be a lot of beneficial approaches depending on:
- What kind of data is going to be saved
- How the user is going to interact with the data
- How to determine the modified and the inserted data
- When to sync the data or just to check for updates
- How to modify when the data was modified or synced for the last time

Please, let us know if you have further questions.

Regards,

Anton Dobrev
Telerik
 
Everlive is now Telerik Backend Services, and is part of the Telerik Platform.
 
0
Igor
Top achievements
Rank 1
answered on 03 May 2014, 04:49 PM
Thanks for your help,

I have recieved data from the backend by using: 

var el = new Everlive('key');
                                var data = elbb.data('tableName');
                                data.get()        
                                .then(function(data){   
//my function
}       

then I am getting the data and displaying it in "function(data)"

is there a way to put the whole var data into sqlite or similar local storage and use "function(data)" again?
like this
//when online - update
var localdata = data;

//when offline
localdata 
.then(function(data){   
//my function
}


0
Igor
Top achievements
Rank 1
answered on 03 May 2014, 05:01 PM
Thanks for your suggestions, I would like to use WebSQL to do this

From looking at the example it looks like I have to:
-get the table from var data
-use the local table
-edit function for local table

Can you tell me if this is the only way, or can I put the full var data including the function in WebSQL
0
Igor
Top achievements
Rank 1
answered on 03 May 2014, 06:16 PM
I have decided to use datasource and websql

Can you please tell me how to use:
- A Kendo UI DataSource that uses WebSQL for local data persistence - here is a demo with full CRUD example. 
http://stackoverflow.com/questions/13496254/how-to-query-a-local-websql-db-with-kendo-ui

to:
1. store the type in local storage
var el = new Everlive('api-key);
    var data = el.data('type-name);

2. display it with KendoUI

0
Igor
Top achievements
Rank 1
answered on 03 May 2014, 07:44 PM
Please ignore all past comments,

I am now using sqlite effectively.

can you provide a code snippet?

add the el.data('table') to sqlite storage
0
Accepted
Anton Dobrev
Telerik team
answered on 05 May 2014, 03:37 PM
Hello Igor,

The means of retrieving items from Backend Services using the JavaScript SDK are summarized in this documentation article.

Basically, after initializing the Everlive global object, you can point it to a given content type and retrieve the data in the following fashion:
var el = new Everlive('api-key');
el.data('MyContentType').get().then(successCallback, errorCallback);

If the request to the server ends successfully, the successCallback function will receive an array with JSON objects.

Before that, you should have a running local SQLite instance with properly mapped tables. For instance, here is a sample script that creates a table "Activities" if such does not exist:

app.createTable = function() {
    var db = app.db;
    db.transaction(function(tx) {
        tx.executeSql("CREATE TABLE IF NOT EXISTS Activities(ID INTEGER PRIMARY KEY ASC, activityText TEXT, createdAt DATETIME, retrievedAt DATETIME, serverId TEXT)", []);
    });
}

The table is created with a name "Activities" and has the following columns:
  • ID - primary key, auto-incrementing.
  • activityText - TEXT field.
  • createdAt - DATETIME field.
  • retrievedAt - DATETIME field.
  • serverId - TEXT field.
Notice that the type of the column fields should match the type of the fields of the server entities, so that we are secure when working with dates, numbers, strings, etc., and switching between the server and local contexts. We would also like to keep the server Id of the activities (serverId) and store a timestamp for each of them (retrievedAt) so that we know the last time we have populated the local version from the server.

After the database is prepared, we can fetch the items from Backend Services and pass a success and error callback functions:

function fetchActivities() {
    var el = new Everlive('your-api-key-here');
    el.data('Activities').get().then(app.addActivity, app.onError);
}

In the app.addActivity function we will iterate over the array and insert a row in the local database for each array member:

app.addActivity = function(activities) {
    var db = app.db;
    db.transaction(function(tx) {
        var i;
        var len = activities.result.length;
        var activity;
        for (i = 0; i < len; i++) {
            activity = activities.result[i];
             
            var activityText = activity.Text;
            var createdAt = activity.createdAt;
            var retrievedAt = new Date();
            var serverId = activity.Id;
 
            tx.executeSql("INSERT INTO Activities(activityText, createdAt, retrievedAt, serverId) VALUES (?,?,?,?)",
                          [activityText, createdAt, retrievedAt, serverId],
                          app.onSuccess,
                          app.onError);
        }
    });
}

For operating with the records in the local database, we should rely on SQL statements like:

db.transaction(function(tx) {
        tx.executeSql("SELECT * FROM Activities", [],
                      successCallback,
                      errorCallback);
    });

These snippets were created, based on the following articles:

Please note that the SQLite plugin is not fully supported in the AppBuilder simulator and will drop the database each time it is restarted. Keep the simulator open in order to keep the database running and click the "Reload" button to simulate a new app start.

Please, let us know if you have questions.

Regards,

Anton Dobrev
Telerik
 
Everlive is now Telerik Backend Services, and is part of the Telerik Platform.
 
Tags
General Discussion
Asked by
Igor
Top achievements
Rank 1
Answers by
Anton Dobrev
Telerik team
Igor
Top achievements
Rank 1
Share this question
or