Flash Builder 移动应用程序中的数据库(Action Script 3.0)

标签 database actionscript-3 apache-flex actionscript flash-builder

我正在尝试使用 adobe flash builder 4.6 为 android 构建一个简单的手机电话簿应用程序,但是当我尝试运行应用程序调试器时,它总是给我一些错误……我在我的项目中发布了所有代码,请采纳一看:(

数据库处理器类:

package ActionScript
{
import air.net.URLMonitor;

import flash.data.SQLConnection;
import flash.data.SQLResult;
import flash.data.SQLStatement;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
import flash.net.URLLoader;
import flash.net.URLRequest;

import mx.collections.ArrayCollection;

import views.NewContactView;
import views.PhoneBookHomeView;






public class dbHandler
{

    private var urlMonitor:URLMonitor;
    private var urlLoader:URLLoader;  
    private var urlRequest:URLRequest;  
    private var sqlConnection:SQLConnection;
    private var db:File;
    private var allContacts:ArrayCollection = new ArrayCollection();

    public function dbHandler()
    {
        trace("dbHandler object was created");
        openDb();
    }

    private function openDb():void
    {
        db = File.applicationStorageDirectory.resolvePath("DataBase.db");

        sqlConnection = new SQLConnection();   
        sqlConnection.addEventListener(SQLErrorEvent.ERROR, onSQLError);

        if(db.exists) 
        {
            trace("DataBase exists");
            sqlConnection.addEventListener(SQLEvent.OPEN, onOpenDb);

        } else {
            trace("DataBase does not exist");
            sqlConnection.addEventListener(SQLEvent.OPEN, onCreateDb);

        }

        sqlConnection.openAsync(db);
    }

    private function onCreateDb(event:SQLEvent):void 
    {
        trace("The database was created");
        createTable(); 
    }

    private function onOpenDb(e:SQLEvent):void 
    {      
        trace("The database was opened");

        if(SQLConnection(e.target).connected)
        {
            trace("SQL Connection is connected");
        }           

    } 

    private function onSQLError(e:SQLErrorEvent):void 
    {     
        var err:String = "-> Error id :" 
            + e.error.errorID 
            + " \ -> Details:" 
            + e.error.details;

        trace ("SQL Error :" + err + "->Error");
    }  

    private function createTable():void
    {
        var sqlText:String = "CREATE TABLE IF NOT EXISTS contacts ( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
        " name TEXT,value TEXT );";
        trace("Creating table by : " + sqlText);
        var createTableSQL:SQLStatement = new SQLStatement();
        createTableSQL.addEventListener(SQLEvent.RESULT, onTable);
        createTableSQL.addEventListener(SQLErrorEvent.ERROR, onSQLError);
        createTableSQL.sqlConnection = sqlConnection;
        createTableSQL.text = sqlText;
        createTableSQL.execute();
    }

    private function onTable(e:SQLEvent):void 
    { 
        trace("The table was created");      
    }

    public function deleteContact(id:int):void
    {      
        var sqlText:String = "DELETE FROM contacts WHERE _id = " + id;
        trace("Deleting item  (id="+id+") by:"+sqlText);
        var deleteTeamSQL:SQLStatement = new SQLStatement();
        deleteTeamSQL.sqlConnection = sqlConnection;
        deleteTeamSQL.addEventListener(SQLEvent.RESULT, onDelete);
        deleteTeamSQL.addEventListener(SQLErrorEvent.ERROR, onSQLError);
        deleteTeamSQL.text = sqlText;
        deleteTeamSQL.execute();                  
    }

    private function onDelete(e:SQLEvent):void 
    {
        trace("item was deleted");
    } 

    public function getAll():ArrayCollection
    {
        var sqlText:String = "SELECT * FROM contacts";
        trace("Geting all contacts by: "+sqlText);
        var getAllSQL:SQLStatement = new SQLStatement();
        getAllSQL.sqlConnection = sqlConnection;
        getAllSQL.addEventListener(SQLEvent.RESULT, ongetAll);
        getAllSQL.addEventListener(SQLErrorEvent.ERROR, onSQLError);
        getAllSQL.text = sqlText;
        getAllSQL.execute();
                return allContacts;
    }

    private function ongetAll(e:SQLEvent):void
    {
        trace("All contacts were got");
            var selectSQL:SQLStatement = SQLStatement(e.target); 
            var result:SQLResult = selectSQL.getResult();  
            if(result.complete)
            {
                if(result.data)
                {

                    for each(var contact:Object in result.data)
                    {
                        var obj:Object = { 
                            Name:contact["name"],
                            Value:contact["value"]
                        };
                    allContacts.addItem(obj);   

                    }
                }
            }
    }

    public function insert(name:String , value:String):void{
        var sqlText:String = "INSERT INTO contacts (name,value) VALUES ('" +
            name +
            "','" +
            value  +
            "')";
        trace("Inserting into contacts by: "+sqlText);
        var insertSQL:SQLStatement = new SQLStatement();
        insertSQL.sqlConnection = sqlConnection;
        insertSQL.addEventListener(SQLEvent.RESULT, onInsert);
        insertSQL.addEventListener(SQLErrorEvent.ERROR, onSQLError);
        insertSQL.text = sqlText;
        insertSQL.execute();
    }

    private function onInsert(event:SQLEvent):void
    {
        trace("Record inserted");

    }

}
  }

主页 View :

<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009" 
    xmlns:s="library://ns.adobe.com/flex/spark" title="Contacts"
    preinitialize="preinitializeHandler(event)">
<fx:Script>
    <![CDATA[
        import ActionScript.dbHandler;

        import mx.collections.ArrayCollection;
        import mx.collections.ArrayList;
        import mx.events.FlexEvent;

        import spark.components.ViewNavigator;
        import spark.events.IndexChangeEvent;

        import views.NewContactView;
        import views.PhoneBookHomeView;


        private var conn:SQLConnection;
        private var initComplete:Boolean = false;
        private var sqlStat:SQLStatement;
        private var sqlConnection:SQLConnection;
        [Bindable]
        public var contacts:ArrayList;

        public var dbHandlerOBJ:dbHandler = new dbHandler();




        protected function button1_clickHandler(event:MouseEvent):void
        {
            navigator.pushView(NewContactView , null);
        }


        protected function preinitializeHandler(event:FlexEvent):void
        {
            PhoneBookList.dataProvider = dbHandlerOBJ.getAll(); 
        }

    ]]>
</fx:Script>
<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:navigationContent>
    <s:Button label="Search"/>
</s:navigationContent>
<s:List left="0" right="0" top="0" bottom="80" id="PhoneBookList" change="">
<s:itemRenderer>
    <fx:Component>
    <s:IconItemRenderer label="label" messageField="Message"/>
    </fx:Component>
</s:itemRenderer>
</s:List>
<s:Button left="5" right="5" top="677" bottom="10"  label="Add New Contact" click="button1_clickHandler(event)"/>

调试错误:

[SWF] PhoneBook.swf - 3,451,124 bytes after decompression
dbHandler object was created
DataBase exists
Geting all contacts by: SELECT * FROM contacts
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at views::PhoneBookHomeView/preinitializeHandler()[C:\Users\Adobe Flash                     Builder 4.6\PhoneBook\src\views\PhoneBookHomeView.mxml:40]
at views::PhoneBookHomeView/___PhoneBookHomeView_View1_preinitialize()[C:\Users\Adobe Flash Builder 4.6\PhoneBook\src\views\PhoneBookHomeView.mxml:4]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.core::UIComponent/dispatchEvent()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:13152]
at mx.core::UIComponent/initialize()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7624]
at spark.components::View/initialize()[E:\dev\4.y\frameworks\projects\mobilecomponents\src\spark\components\View.as:999]
at views::PhoneBookHomeView/initialize()
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::childAdded()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7495]
at mx.core::UIComponent/addChildAt()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7199]
at spark.components::Group/addDisplayObjectToDisplayList()[E:\dev\4.y\frameworks\projects\spark\src\spark\components\Group.as:2037]
at spark.components::Group/http://www.adobe.com/2006/flex/mx/internal::elementAdded()[E:\dev\4.y\frameworks\projects\spark\src\spark\components\Group.as:1628]
at spark.components::Group/addElementAt()[E:\dev\4.y\frameworks\projects\spark\src\spark\components\Group.as:1387]
at spark.components::Group/addElement()[E:\dev\4.y\frameworks\projects\spark\src\spark\components\Group.as:1345]
at spark.components::SkinnableContainer/addElement()[E:\dev\4.y\frameworks\projects\spark\src\spark\components\SkinnableContainer.as:761]
at spark.components::ViewNavigator/createViewInstance()[E:\dev\4.y\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:2018]
at spark.components::ViewNavigator/commitNavigatorAction()[E:\dev\4.y\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1932]
at spark.components::ViewNavigator/commitProperties()[E:\dev\4.y\frameworks\projects\mobilecomponents\src\spark\components\ViewNavigator.as:1301]
at mx.core::UIComponent/validateProperties()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:8219]
at mx.managers::LayoutManager/validateProperties()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\LayoutManager.as:597]
at mx.managers::LayoutManager/doPhasedInstantiation()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\LayoutManager.as:783]
at mx.managers::LayoutManager/doPhasedInstantiationCallback()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\LayoutManager.as:1180]

我认为数据库不存在......但我不知道为什么我的类(class)不起作用:(

最佳答案

当触发预初始化事件时,您无法从实例中获取/读取任何内容。

如果您引用官方文档(http://livedocs.adobe.com/flex/3/html/help.html?content=containers_intro_3.html,“关于初始化和创建完成事件”部分)或该链接:http://www.tutorialspoint.com/flex/flex_life_cycle_phases.htm ,当预初始化事件被触发时,您的对象实例是原始的(也就是空的)。

您应该将 PhoneBookList.dataProvider = dbHandlerOBJ.getAll(); 插入到 Initialized 或更好的 CreationComplete 事件中。

关于Flash Builder 移动应用程序中的数据库(Action Script 3.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320580/

相关文章:

actionscript-3 - 优化 AS3 SWF 文件的大小?

apache-flex - 柔性 : HTTP request error #2032

php - Flashbuilder、PHP 和 MySQL

actionscript-3 - 在 Adob​​e Flex 中动态创建菜单?

database - 连接到 Shopify 或 Wordpress 的 Onix 文件 [帮助]

php - 虽然循环使用单选按钮为许多用户将值插入数据库

sql - 今天和昨天找个时间

java - servlet 无法保存到数据库

actionscript-3 - Flash AS3 多点触摸事件处理程序

actionscript-3 - 为什么不能使用 "final"是一个安全问题?