How to create a OData List? - android

I want to create a OList, so that every position opened a new OList if I tap on it. At this moment I have following code:
function readCustomerSuccessCallback(data, response) {
var citems = [];
for (var i = 0; i < data.results.length; i++) {
var citem = new sap.m.StandardListItem(
{
type: "Active",
tap : readProducts(data.results[i].STATION_ID),
title: data.results[i].CUSTOMER_NAME,
description: data.results[i].STATION_ID
});
citems.push(citem);
}
var oList = new sap.m.List({
headerText : "Customers",
setGrowingScrollToLoad: true,
items : citems,
press: function(e) {
console.log(oList.getSelectedItems());
}
});
oList.placeAt("content"); // place model onto UI
}
function readProducts(category) {
console.log("read request started");
startTime = new Date();
if (!haveAppId()) {
return;
}
sURL = myUrl;
var oHeaders = {};
oHeaders['Authorization'] = authStr;
//oHeaders['X-SMP-APPCID'] = appCID; //this header is provided by the logon plugin
var request = {
headers : oHeaders,
requestUri : sURL,
method : "GET"
};
OData.read(request, readProductsSuccessCallback, errorCallback);
}
The function read CustomerSuccesCAllback creates a OList,and if I tap on a field of this list, I want that a new List shows up. For the second step is the function readproducts responsible.
With this code it doesnt work. It shows me not the customers, but only theyre details.
Has anybody an idea?

Change in readCustomerSuccessCallback:
tap: function(e){
readProducts(this.getDescription),
}
//this will stop invoking the function while defining your items

Related

Fetching Data in Google SpreadSheets

I have a problem with this reference From this Site Using Google SpreadSheet as Database. the problem is that. the Android Application cannot fetch the data in a google spreadsheet. The Application can successfully run but couldn't find data in the Spreadsheet.
I Already Updated the codes from the android studio because of the old version used codes. I just copy and paste it and change some of it.
Codes Below:
The Script Link to fetch the Data :
https://script.google.com/macros/s/AKfycbwZJCWoQ7dpC5KwyRM9JYsjCjymQUspAfPmniOApD_CSEoc-LdP/exec?id=16O_OfgKxASgqa2WWQKePJI1jnJMTdb4OyXbUJU6kWH0&sheet=Sheet1
Link of the SpreadSheet :
https://docs.google.com/spreadsheets/d/16O_OfgKxASgqa2WWQKePJI1jnJMTdb4OyXbUJU6kWH0/edit#gid=0
This is the App Script that Fetches the data:
you can also see the app script codes here : App Script Codes.
function doGet(request) {
var output = ContentService.createTextOutput(),
data = {},
id = request.parameters.id,
sheet = request.parameters.sheet,
ss = SpreadsheetApp.openById(id);
data.records = readData_(ss, sheet);
var callback = request.parameters.callback;
if (callback === undefined) {
output.setContent(JSON.stringify(data));
} else {
output.setContent(callback + "(" + JSON.stringify(data) + ")");
}
output.setMimeType(ContentService.MimeType.JSON);
return output;
}
function readData_(ss, sheetname, properties) {
if (typeof properties == "undefined") {
properties = getHeaderRow_(ss, sheetname);
properties = properties.map(function(p) { return p.replace(/\s+/g, '_'); });
}
var rows = getDataRows_(ss, sheetname),
data = [];
for (var r = 0, l = rows.length; r < l; r++) {
var row = rows[r],
record = {};
for (var p in properties) {
record[properties[p]] = row[p];
}
data.push(record);
}
return data;
}
function getDataRows_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
}
function getHeaderRow_(ss, sheetname) {
var sh = ss.getSheetByName(sheetname);
return sh.getRange(1, 1, 1, sh.getLastColumn()).getValues()[0];
}
More Codes From the Link Above or click here for not scrolling back.

Nativescript - Update dynamic textfield source on click

I just want to ask how can I update the dynamic textfield upon a button click? The textfield is dynamic and the value should come from observable.
Code Behind
var observableModule = require("data/observable");
var source = new observableModule.Observable();
var HomePage = function() {};
HomePage.prototype = new BasePage();
HomePage.prototype.constructor = HomePage;
HomePage.prototype.contentLoaded = function(args) {
var page = args.object;
source.textSource = "sample";
var layout = page.getViewById("stackID");
var textField = new TextFieldModule.TextField();
var textFieldBindingOptions = {
sourceProperty: "textSource",
targetProperty: "text",
twoWay: false
};
textField.bind(textFieldBindingOptions, source);
layout.addChild(textField);
}
HomePage.prototype.buttonTap = function() {
source.textSource = "new word";
source.update();
}
XML
<stack-layout loaded="contentLoaded" id="stackID">
<Button tap="buttonTap" text="Update" />
</stack-layout>
I was able to find on how to update the source on click.
HomePage.prototype.onTap = function() {
source.set("textSource", "new word");
}
Source: http://docs.nativescript.org/cookbook/data/observable

CardIO Plugin - Issues with manually entering Card details on Android

I have implemented the following CardIO plugin in my Ionic App:
https://github.com/card-io/card.io-Cordova-Plugin
This works fine on iOS. However, on Android, when I use the keyboard option in the Camera Screen to manually type in the card details, it first loads the correct screen momentarily, and then jumps back to the first screen (Sign Up screen in this case) of the app. While debugging the app flow, I saw that the callback for Card IO is working fine, but there seems to be an issue when Ionic handles the event.
Any help greatly appreciated!
Following is the code in my controller:
$scope.$on('$ionicView.beforeEnter', function()
{
$scope.creditCardScanning();
}
$scope.creditCardScanning = function(){
var cardIOResponseFields = [
"cardType",
"redactedCardNumber",
"cardNumber",
"expiryMonth",
"expiryYear",
"cvv",
"postalCode"
];
var onCardIOComplete = function(response) {
for (var i = 0; i < cardIOResponseFields.length; i++) {
var field = cardIOResponseFields[i];
}
var cardName = response[cardIOResponseFields[0]].toUpperCase();
for (i = 0; i < $scope.cardtype.length; i++) {
var cardTypeDict = $scope.cardtype[i];
if(cardTypeDict.card_type_name === cardName){
document.getElementById('cardtype').selectedIndex = i;
$scope.params.card_type = cardName;
break;
}
}
document.getElementById('cardNumber').value = response[cardIOResponseFields[2]];
$scope.params.card_number = response[cardIOResponseFields[2]];
var expMonthVal = response[cardIOResponseFields[3]];
for(i=0;i < $scope.expmonth.length; i++) {
var expMonthDict = $scope.expmonth[i];
if(expMonthDict.value === expMonthVal){
document.getElementById('expmonth').selectedIndex = i;
$scope.params.expiration_month = expMonthDict.value;
break;
}
}
for (i = 0; i < $scope.expyear.length; i++) {
var expYearDict = $scope.expyear[i];
if(expYearDict.value === response[cardIOResponseFields[4]]){
document.getElementById('expyear').selectedIndex = i;
$scope.params.expiration_year = response[cardIOResponseFields[4]];
break;
}
}
document.getElementById('cvv').value = response[cardIOResponseFields[5]];
$scope.params.security_code = response[cardIOResponseFields[5]];
};
var onCardIOCancel = function() {
console.log("card.io scan cancelled");
};
var onCardIOCheck = function (canScan) {
console.log("card.io canScan? " + canScan);
var scanBtn = document.getElementById("scanBtn");
if (!canScan) {
console.log("Cannot scan card");
}
scanBtn.onclick = function (e) {
CardIO.scan({
"requireExpiry": true,
"requireCVV": true,
"requirePostalCode": false,
"shows_first_use_alert": true,
"disable_manual_entry_buttons": false
},
onCardIOComplete,
onCardIOCancel
);
}
};
CardIO.canScan(onCardIOCheck);
}
And in my view, I am calling the function to load the next page, once the card details are successfully entered and the "Next" Button is tapped.

Lokijs DB data removed after rerun using ionic run command?

I am working on a ionic project and trying to use LokiJS. Below is my code,
controller,
$scope.test ={birthdays:[]};
$ionicPlatform.ready(function() {
BirthdayService.initDB();
BirthdayService.getAllBirthdays().then(function(birthdays){
console.log("birthdays=",birthdays);// gives empty array second run...
//var bday1 = {Name:"abrj",Date:new Date()};
//var bday2 = {Name:"abrj2",Date:new Date()};
//BirthdayService.addBirthday(bday1);
//BirthdayService.addBirthday(bday2); added birthdays during the first run.
});
});
I am using cordova-fs-adapter and cordova-file-plugin.
below is my service for adapter integration,
(function() {
angular.module('starter').factory('BirthdayService', ['$q', 'Loki', BirthdayService]);
function BirthdayService($q, Loki) {
var _db;
var _birthdays;
function initDB() {
var fsAdapter = new LokiCordovaFSAdapter({"prefix": "loki"});
_db = new Loki('birthdaysDB',
{
autosave: true,
autosaveInterval: 1000, // 1 second
adapter: fsAdapter
});
};
function getAllBirthdays() {
return $q(function (resolve, reject) {
var options = {
birthdays: {
proto: Object,
inflate: function (src, dst) {
var prop;
for (prop in src) {
if (prop === 'Date') {
dst.Date = new Date(src.Date);
} else {
dst[prop] = src[prop];
}
}
}
}
};
_db.loadDatabase(options, function () {
_birthdays = _db.getCollection('birthdays');
if (!_birthdays) {
_birthdays = _db.addCollection('birthdays');
}
resolve(_birthdays.data);
});
});
};
function addBirthday(birthday) {
console.log("Birthdays=",_birthdays);
_birthdays.insert(birthday);
};
function updateBirthday(birthday) {
_birthdays.update(birthday);
};
function deleteBirthday(birthday) {
_birthdays.remove(birthday);
};
return {
initDB: initDB,
getAllBirthdays: getAllBirthdays,
addBirthday: addBirthday,
updateBirthday: updateBirthday,
deleteBirthday: deleteBirthday
};
}
})();
In first run I am inserting two documents into the birthdays collections.On second run when I trying to check whether they have persisted, they weren't. I know I am doing something wrong.Do suggest.Local storage also gets cleared everytime i rerun(ionic run android)?!

IndexedDB – search for specific data? How to find the values from another value in a row?

Below is my example that I have. So far it does the following.
Enter in 3 values to a row
Retrieve all the values from all rows on load
Place all the values from each row and print them to screen that was
retrieved from the above step.
The part that I need help with is trying to find all the values of one row based on a value that exists in that row.
If a row contains the values name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ I would like to get all the data of that row when some one searches for ‘Andrew’
So far if you look at the function ‘searchItems’ you will see that I am trying to find data based on the value of the search input. The problem I am having is all I can get it to do is alert an “undefined” response.
How can I write the function to have it find things like described above
Also one step further. How can i edit the data that is in the row that was found based on the search input? (I have not written that function yet)
html
<!--jquery-2.1.4.js-->
<body>
<input type="text" id="dataGoesHere" />
<input type="text" id="moredataGoesHere" />
<input type="text" id="mostdataGoesHere" />
<button id="clickme">Save</button>
<div id="saved"></div>
<br><br>
<input type="text" id="searchString" />
<button id="search">search</button>
</body>
js
$(document).ready(function() {
myDb = function () {
var name = "test",
version = "1",
db,
testStoreName = "exampleStore",
testIndexName = "testIndexName",
addToTestIndex = false,
init = function () {
var deferred = $.Deferred(),
openRequest = indexedDB.open(name, version);
openRequest.onupgradeneeded = dbUpgrade;
openRequest.onsuccess = dbOpen;
openRequest.onerror = dbError;
return deferred.promise();
function dbUpgrade(evt) {
//here our db is at evt.target.result here we can adjust stores and indexes
var thisDb = evt.target.result, //the current db we are working with
newStore = thisDb.createObjectStore(testStoreName, {keyPath: "id", autoIncrement: true});
//Using indexes, you can target specific keys, this can be an array!
newStore.createIndex("testIndexKey", "testIndexKey", {unique : false});
console.log("Doing an upgrade");
}
function dbOpen(evt) {
console.log("DB successfully opened");
db = evt.target.result;
deferred.resolve();
getAllItems (function (items) {
var len = items.length;
for (var i = 0; i < len; i += 1) {
console.log(items[i]);
$('#saved').append('<p>'+items[i].item + ' ' + items[i].george + ' ' + items[i].column3 + ' ' + items[i].id + '</p>');
}
});
}
function dbError(error) {
console.log("DB Error");
console.log(error);
deferred.reject(error);
}
},
add = function(item, bob, villa) {
var itemToAdd = {"item" : item, "george" : bob, "column3" : villa},
objStore,
request,
deferred = $.Deferred();
if (!addToTestIndex) {
//here we will add half the entries to the index
//See http://stackoverflow.com/questions/16501459/javascript-searching-indexeddb-using-multiple-indexes for a better example
addToTestIndex = !addToTestIndex;
itemToAdd.testIndexKey = "This is a test";
}
//first get the object store with the desired access
objStore = db.transaction([testStoreName], "readwrite").objectStore(testStoreName);
//next create the request to add it
request = objStore.add(itemToAdd);
request.onsuccess = function (evt) {
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject(evt);
};
return deferred.promise();
},
get = function (index) {
//Since our store uses an int as a primary key, that is what we are getting
//The cool part is when you start using indexes...
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(parseInt(index));
request.onsuccess = function (evt) {
console.log(evt);
deferred.resolve(evt.target.result);
};
request.onerror = function (evt) {
deferred.reject("DBError: could not get " + index + " from " + testStoreName);
};
return deferred.promise();
},
getAllItems = function(callback) {
var trans = db.transaction(testStoreName, IDBTransaction.READ_ONLY);
var store = trans.objectStore(testStoreName);
var items = [];
trans.oncomplete = function(evt) {
callback(items);
};
var cursorRequest = store.openCursor();
cursorRequest.onerror = function(error) {
console.log(error);
};
cursorRequest.onsuccess = function(evt) {
var cursor = evt.target.result;
if (cursor) {
items.push(cursor.value);
cursor.continue();
}
};
},
searchItems = function(searchString) {
var deferred = $.Deferred(),
store = db.transaction([testStoreName], "readonly").objectStore(testStoreName);
request = store.get(searchString);
request.onerror = function(event) {
// Handle errors!
alert("error");
};
request.onsuccess = function(event) {
alert('start seach')
// Do something with the request.result!)
alert(event.target.result);
alert('end search')
};
};
return {
init: init,
get: get,
add: add,
getAllItems: getAllItems,
searchItems: searchItems
};
}
var db = new myDb();
db.init().then(function () {
$("#clickme").click(function(evt) {
//add, then we will get the added item from the db
console.log("Adding new item to db");
db.add($('#dataGoesHere').val(), $('#moredataGoesHere').val(), $('#mostdataGoesHere').val())
.then(function (res) {
return db.get(res);
})
.then(function (res) {
$('#saved').append('<p>'+res.item+' '+res.george+' '+res.column3+'</p>');
});
});
$("#search").click(function(evt) {
// search for a specific row
console.log("searching");
db.searchItems($('#searchString').val());
});
})
});
First thing (and could be the probable cause): Are you having an index on the key you are trying to search? In you case, for data as name: ‘Andrew’ , phone: ’555-55555’, address: ’123 over there’ if you trying to search for "Andrew", then you should be having an index created on "name". If it is not there then you will not be able to make a search and that's what probably could be happening.
Next: In the data store there could be more than one rows with name as Andrew, so you can have a cursor open using the index and then loop through all value and get the desired one. Something like (I am just throwing you an idea through this code snippet):
var objectStoreHandler = transaction.objectStore(selectDataObj.tblName);
var indexHandler = objectStoreHandler.index(selectDataObj.whereColObj.whereColNameArr[0]);
var cursorHandler = indexHandler.openCursor(keyRange);
cursorHandler.onsuccess = function (event) {
var cursor = event.target.result;
if (cursor) {
console.log("!!!!!");
if (cursor.value != null && cursor.value != undefined) {
resultArr.push(cursor.value);
}
cursor["continue"]();
} else {
console.log("################### " + resultArr);
return successCallBack(resultArr);
}
return;
};

Categories

Resources