Cordova SQL 代码不起作用

Posted

技术标签:

【中文标题】Cordova SQL 代码不起作用【英文标题】:Cordova SQL code does not work 【发布时间】:2013-11-07 20:15:38 【问题描述】:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>

<!--
This is an example that shows how to create an application that uses
an embedded sqlite database
in a mobile device (iphone,ipod,ipad,android using phonegap, jquery
and sqlite.

Your phonegap project will already contain the phonegap.js.

You will need to download and add to your project the jquery.min.js
file

The application will create a database called WebSqlDb with a
table in it called User, which contains three fields  UserId,
FirstName and LastName

When the application is run the firsttime, if the local database does
not exist, the application
will create the database and the table.

The application shows two text boxes which you can use to add values
to the database using the add record button

The application also has a refresh button which will get the data from
the database and show it on the screen

When the application is run on the device the onBodyLoad() function is
called, which sets up the database and table

The Add Record button calls the AddValueToDB() function

The Refresh button calls the ListDBValues() function

There are a few alert statements in this application, which are only
there for debuggin purposes.  They look like this
alert("DEBUGGING: followed by some text");

These are only in the application to indicate where the application is
at when it is processing functions, etc

You will need to comment these out before you deploy/sell your
application

-->


<!-- Change this if you want to allow scaling -->
   <meta name="viewport" content="width=default-width; user-
scalable=no" />
   <meta http-equiv="Content-type" content="text/html;charset=utf-8">

   <title>Embedded Sql Example</title>

<!-- include the next line to use phonegap javascript functions -->
    <script type="text/javascript" charset="utf-8" src="phonegap.js"></
script>

// have done above with cordova.js also. 

<!-- include the next line to use jquery functions in your application
you must download this and include the directory your html file is in
-->
        <script type="text/javascript" charset="utf-8" src="jquery.min.js"></
script>

// jquery.min.js lives next to index.html

<!-- main scripts used in this example -->
 <script type="text/javascript" charset="utf-8">

// global variables
var db;
var shortName = 'WebSqlDB';
var version = '1.0';
var displayName = 'WebSqlDB';
var maxSize = 65535;

// this is called when an error happens in a transaction
function errorHandler(transaction, error) 
   alert('Error: ' + error.message + ' code: ' + error.code);



// this is called when a successful transaction happens
function successCallBack() 
   alert("DEBUGGING: success");



function nullHandler();

// called when the application loads
function onBodyLoad()

// This alert is used to make sure the application is loaded correctly
// you can comment this out once you have the application working
alert("DEBUGGING: we are in the onBodyLoad() function");

 if (!window.openDatabase) 
   // not all mobile devices support databases  if it does not, the
following alert will display
   // indicating the device will not be albe to run this application
   alert('Databases are not supported in this browser.');
   return;
 

// this line tries to open the database base locally on the device
// if it does not exist, it will create it and return a database
object stored in variable db
 db = openDatabase(shortName, version, displayName,maxSize);

// this line will try to create the table User in the database just
created/openned
 db.transaction(function(tx)

  // you can uncomment this next line if you want the User table to be
empty each time the application runs
  // tx.executeSql( 'DROP TABLE User',nullHandler,nullHandler);

  // this line actually creates the table User if it does not exist
and sets up the three columns and their types
  // note the UserId column is an auto incrementing column which is
useful if you want to pull back distinct rows
  // easily from the table.
   tx.executeSql( 'CREATE TABLE IF NOT EXISTS User(UserId INTEGER NOT
NULL PRIMARY KEY, FirstName TEXT NOT NULL, LastName TEXT NOT NULL)',
[],nullHandler,errorHandler);
 ,errorHandler,successCallBack);



// list the values in the database to the screen using jquery to
update the #lbUsers element
function ListDBValues() 

 if (!window.openDatabase) 
  alert('Databases are not supported in this browser.');
  return;
 


// this line clears out any content in the #lbUsers element on the
page so that the next few lines will show updated
// content and not just keep repeating lines
 $('#lbUsers').html('');

// this next section will select all the content from the User table
and then go through it row by row
// appending the UserId  FirstName  LastName to the  #lbUsers element
on the page
 db.transaction(function(transaction) 
   transaction.executeSql('SELECT * FROM User;', [],
     function(transaction, result) 
      if (result != null && result.rows != null) 
        for (var i = 0; i < result.rows.length; i++) 
          var row = result.rows.item(i);
          $('#lbUsers').append('<br>' + row.UserId + '. ' +
row.FirstName+ ' ' + row.LastName);
        
      
     ,errorHandler);
 ,errorHandler,nullHandler);


 return;



// this is the function that puts values into the database using the
values from the text boxes on the screen
function AddValueToDB() 

 if (!window.openDatabase) 
   alert('Databases are not supported in this browser.');
   return;
 

// this is the section that actually inserts the values into the User
table
 db.transaction(function(transaction) 
   transaction.executeSql('INSERT INTO User(FirstName, LastName)
VALUES (?,?)',[$('#txFirstName').val(), $('#txLastName').val()],
     nullHandler,errorHandler);
   );


// this calls the function that will show what is in the User table in
the database
 ListDBValues();

 return false;





</script>
</head>
<body onload="onBodyLoad()">
<h1>WebSQL</h1>
<input id="txFirstName" type="text" placeholder="FirstName">
<input id="txLastName" type="text" placeholder="Last Name">
<input type="button" value="Add record" onClick="AddValueToDB()">
<input type="button" value="Refresh" onClick="ListDBValues()"> <br>
<br>
<span style="font-weight:bold;">Currently stored values:</span>
<span id="lbUsers"></span>
</body>
</html>

来自logcat:

E/Web Console(21030): Uncaught ReferenceError: AddValueToDB is not defined:204
E/DataRouter(  154): Opening of the USB File failed fd is -1 & errno is 2

在搜索 cordova/phonegap sql 示例时,上面的代码被广泛引用。对我来说它不起作用。应用程序的警报不会引发错误消息,并且 logcat 抱怨源中定义的函数是未知的。我正在使用cli中的cordova/phonegap 3.1.0。该应用程序在三星 SGS2/Android 4.1.2 上运行。为什么这个演示应用程序不起作用?

【问题讨论】:

【参考方案1】:

我认为问题出在正文 onload="onbodyLoad()" 上。使用 phonegap,您必须使用 deviceready 事件的事件侦听器确保设备实际上已准备好。这是我开始工作的代码。确保您已下载并包含 jquery。我使用的是 1.7.2 版。我还将 javascript 分离到一个单独的文件中,以便我可以使用 jslint 来调试它。我还将文档类型更改为 html 5。

索引.html:

<!DOCTYPE html>
<html>
<head>
    <title>Embedded Sql Example</title>
    <meta name="viewport" content="width=default-width; user-scalable=no" />
    <meta http-equiv="Content-type" content="text/html;charset=utf-8">

    <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

    <script type="text/javascript" charset="utf-8" src="js/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
        app.initialize();
    </script>
</head>
<body>
    <h1>WebSQL</h1>
    <input id="txFirstName" type="text" placeholder="FirstName">
    <input id="txLastName" type="text" placeholder="Last Name">
    <input type="button" value="Add record" onClick="AddValueToDB()">
    <input type="button" value="Refresh" onClick="ListDBValues()"> <br>
    <br/>
    <span style="font-weight:bold;">Currently stored values:</span>
    <span id="lbUsers"></span>
</body>
</html>

Index.js:

var app = 
  // Application Constructor
  initialize: function() 
    this.bindEvents();
  ,
  // Bind Event Listeners
  //
  // Bind any events that are required on startup. Common events are:
  // 'load', 'deviceready', 'offline', and 'online'.
  bindEvents: function() 
    document.addEventListener('deviceready', this.onDeviceReady, false);
  ,
  // deviceready Event Handler
  //
  // The scope of 'this' is the event. In order to call the 'receivedEvent'
  // function, we must explicity call 'app.receivedEvent(...);'
  onDeviceReady: function() 
    onBodyLoad();
  ,
;


// global variables
var db;
var shortName = 'WebSqlDB';
var version = '1.0';
var displayName = 'WebSqlDB';
var maxSize = 65535;

// this is called when an error happens in a transaction
function errorHandler(transaction, error) 
  alert('Error: ' + error.message + ' code: ' + error.code);


// this is called when a successful transaction happens
function successCallBack() 
  alert("DEBUGGING: success");


function nullHandler() 

// called when the application loads
function onBodyLoad() 
  // This alert is used to make sure the application is loaded correctly
  // you can comment this out once you have the application working
  alert("DEBUGGING: we are in the onBodyLoad() function");

  if (!window.openDatabase) 
    // not all mobile devices support databases  if it does not, the following alert will display
    // indicating the device will not be albe to run this application
    alert('Databases are not supported in this browser.');
    return;
  

  // this line tries to open the database base locally on the device
  // if it does not exist, it will create it and return a database object stored in variable db
  db = openDatabase(shortName, version, displayName,maxSize);

  // this line will try to create the table User in the database just created/openned
  db.transaction(function(tx)

  // you can uncomment this next line if you want the User table to be empty each time the application runs
  // tx.executeSql( 'DROP TABLE User',nullHandler,nullHandler);

  // this line actually creates the table User if it does not exist and sets up the three columns and their types
  // note the UserId column is an auto incrementing column which is useful if you want to pull back distinct rows
  // easily from the table.
  tx.executeSql( 'CREATE TABLE IF NOT EXISTS User(UserId INTEGER NOT NULL PRIMARY KEY, FirstName TEXT NOT NULL, LastName TEXT NOT NULL)',
    [], nullHandler, errorHandler);
    , errorHandler, successCallBack);



// list the values in the database to the screen using jquery to update the #lbUsers element
function ListDBValues() 
  if (!window.openDatabase) 
    alert('Databases are not supported in this browser.');
    return;
  


  // this line clears out any content in the #lbUsers element on the page so that the next few lines will show updated
  // content and not just keep repeating lines
  $('#lbUsers').html('');

  // this next section will select all the content from the User table and then go through it row by row
  // appending the UserId  FirstName  LastName to the  #lbUsers element on the page
  db.transaction(function(transaction) 
    transaction.executeSql('SELECT * FROM User;', [],
    function(transaction, result) 
      if (result !== null && result.rows !== null) 
        for (var i = 0; i < result.rows.length; i++) 
          var row = result.rows.item(i);
          $('#lbUsers').append('<br>' + row.UserId + '. ' + row.FirstName+ ' ' + row.LastName);
        
      
    , errorHandler);
  , errorHandler, nullHandler);
  return;


// this is the function that puts values into the database using the values from the text boxes on the screen
function AddValueToDB() 
  if (!window.openDatabase) 
    alert('Databases are not supported in this browser.');
    return;
  

  // this is the section that actually inserts the values into the User table
  db.transaction(function(transaction) 
    transaction.executeSql('INSERT INTO User(FirstName, LastName) VALUES (?,?)',[$('#txFirstName').val(), $('#txLastName').val()],
    nullHandler, errorHandler);
  );

  // this calls the function that will show what is in the User table in the database
  ListDBValues();

  return false;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

【讨论】:

感谢您的回复。不幸的是,这里仍然没有功能,虽然我在 logcat 中没有看到任何明显的错误:pastebin.com/24vM2J3T 另外,没有触发任何调试警报。 它适用于我并且触发了调试警报。尝试使用此命令(phonegap create test com.test)创建一个新的 phonegap 项目,然后更改 www/index.html 和 www/js/index.js,并将 jquery-1.7.2.min.js 添加到 www/js。然后运行(phonegap run android)。 logcat 也没有多大帮助。真正有助于调试phonegap的是javascript日志记录和调试:adamwadeharris.com/setup-remote-debugging-phonegap 感谢您的帮助。我的安装一定有问题,我得到了一个表单,但是当我输入数据时,我的设备或模拟器上没有任何活动(警报、列表)。模拟器和手机都会响应在调试控制台中输入警报(“hi”)。这与您的代码、1.7.2 jquery 等有关。

以上是关于Cordova SQL 代码不起作用的主要内容,如果未能解决你的问题,请参考以下文章

相机代码和 Cordova 不起作用

Cordova / Phonegap iOS Safari 和语音合成不起作用

Cordova 背景图像在 Android 上不起作用 [关闭]

AngularJS 中的移动后退按钮与 Cordova/PhoneGap 不起作用

Cordova GeoLocation 在 android 应用程序中不起作用

JavaScript 在 Android 4.4+ 上的 Cordova 应用程序中不起作用