使用phonegap和Sencha Touch访问Android手机通讯录

时间:2012-02-08 10:43:39

标签: javascript android html cordova sencha-touch

请我尝试使用以下代码获取手机上所有联系人的列表。

var App = new Ext.Application({
name: 'SmsthingyApp',
useLoadMask: true,
launch: function () {

    Ext.data.ProxyMgr.registerType("contactstorage",
    Ext.extend(Ext.data.Proxy, {
        create: function(operation, callback, scope) {
        },
        read: function(operation, callback, scope) {
        },
        update: function(operation, callback, scope) {
        },
        destroy: function(operation, callback, scope) {
        }
    })
);

    Ext.regModel("contact", {
        fields: [
            {name: "id", type: "int"},
            {name: "givenName", type: "string"},
            {name: "familyName", type: "string"},
            {name: "emails", type: "auto"},
            {name: "phoneNumbers", type: "auto"}
        ]
    });

    Ext.regStore('contacts',{
        model: "contact",
        proxy: {
                    type: "contactstorage",
                    read: function(operation, callback, scope) {
                        var thisProxy = this;
                        navigator.contacts.find(
                            ['id', 'name', 'emails', 'phoneNumbers', 'addresses'],
                            function(deviceContacts) {
                                //loop over deviceContacts and create Contact model instances
                                var contacts = [];
                                for (var i = 0; i < deviceContacts.length; i++) {
                                    var deviceContact = deviceContacts[ i ];
                                    var contact = new thisProxy.model({
                                        id: deviceContact.id,
                                        givenName: deviceContact.name.givenName,
                                        familyName: deviceContact.name.familyName,
                                        emails: deviceContact.emails,
                                        phoneNumbers: deviceContact.phoneNumbers
                                    });
                                    contact.deviceContact = deviceContact;
                                    contacts.push(contact);
                                }
                                //return model instances in a result set
                                operation.resultSet = new Ext.data.ResultSet({
                                    records: contacts,
                                    total  : contacts.length,
                                    loaded : true
                                });
                                //announce success
                                operation.setSuccessful();
                                operation.setCompleted();
                                //finish with callback
                                if (typeof callback == "function") {
                                    callback.call(scope || thisProxy, operation);
                                }
                            },
                            function (e) { console.log('Error fetching contacts'); },
                            {multiple: true}
                        );
                    }

                }
    });




    Ext.regModel('Sms', {
        idProperty: 'id',
        fields: [
            { name: 'id', type: 'int' },
            { name: 'date', type: 'date', dateFormat: 'c' },
            { name: 'title', type: 'string' },
            { name: 'message', type: 'string' }
        ],
        validations: [
            { type: 'presence', field: 'id' },
            { type: 'presence', field: 'title', message: 'Please select a contact for this sms.' }
        ]
    });

    Ext.regStore('SmsStore', {
        model: 'Sms',
        sorters: [{
            property: 'date',
            direction: 'DESC'
        }],
        proxy: {
            type: 'localstorage',
            id: 'sms-app-localstore'
        },
        getGroupString: function (record) 
        {
            if (record && record.data.date) 
            {
                return record.get('date').toDateString();
            } 
            else 
            {
                return '';
            }
        }
    });

     SmsthingyApp.views.ContactsList = new Ext.List({

        id: 'ContactsList',
        layout: 'fit',
            store:'contacts',
            itemTpl: '{givenName} {familyName}',
            listeners: {'render': function (thisComponent) 
                {
                    SmsthingyApp.views.ContactsList.getStore().load();
                }
            },
            onItemDisclosure: function (record) {
                //Ext.dispatch({
                //    controller: SmsthingyApp.controllers.contacts,
                //    action: 'show',
                //    id: record.getId()
                //});
            }

    });

    SmsthingyApp.views.contactsListContainer = new Ext.Panel({
        id: 'contactsListContainer',
        layout: 'fit',
        html: 'This is the sms list container',
        items: [SmsthingyApp.views.ContactsList],
        dockedItems: [{
            xtype: 'toolbar',
            title: 'Contacts'
        }]
    });




    SmsthingyApp.views.smsEditorTopToolbar = new Ext.Toolbar({
        title: 'Edit SMS',
        items: [
            {
                text: 'Back',
                ui: 'back',
                handler: function () {
                    SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
                }
            },
            { xtype: 'spacer' },
            {
                text: 'Save',
                ui: 'action',
                handler: function () {
                    var smsEditor = SmsthingyApp.views.smsEditor;
                    var currentSms = smsEditor.getRecord();

                 // Update the note with the values in the form fields.
                    smsEditor.updateRecord(currentSms);

                    var errors = currentSms.validate();
                    if (!errors.isValid()) 
                    {
                        currentSms.reject();
                        Ext.Msg.alert('Wait!', errors.getByField('title')[0].message, Ext.emptyFn);
                        return;
                    }

                    var smsList = SmsthingyApp.views.smsList;
                    var smsStore = smsList.getStore();

                    if (smsStore.findRecord('id', currentSms.data.id) === null) 
                    {
                        smsStore.add(currentSms);
                    }
                    else
                    {
                        currentSms.setDirty();
                    }

                    smsStore.sync();
                    smsStore.sort([{ property: 'date', direction: 'DESC'}]);

                    smsList.refresh();

                    SmsthingyApp.views.viewport.setActiveItem('smsListContainer', { type: 'slide', direction: 'right' });
                }
            }
        ]
    });

    SmsthingyApp.views.smsEditorBottomToolbar = new Ext.Toolbar({
        dock: 'bottom',
        items: [
            { xtype: 'spacer' },
            {
                text: 'Send',
                handler: function () {
                    // TODO: Send current sms.
                }
            }
        ]
    });


    SmsthingyApp.views.smsEditor = new Ext.form.FormPanel({
        id: 'smsEditor',
        items: [
            {
                xtype: 'textfield',
                name: 'title',
                label: 'To',
                required: true
            },
            {
                xtype: 'textareafield',
                name: 'narrative',
                label: 'Message'
            }
        ],
        dockedItems:[
                         SmsthingyApp.views.smsEditorTopToolbar,
                         SmsthingyApp.views.smsEditorBottomToolbar
                     ]
    });

    SmsthingyApp.views.smsList = new Ext.List({
        id: 'smsList',
        store: 'SmsStore',
        grouped: true,
        emptyText: '<div style="margin: 5px;">No notes cached.</div>',
        onItemDisclosure: function (record) 
        {
            var selectedSms = record;
            SmsthingyApp.views.smsEditor.load(selectedSms);
            SmsthingyApp.views.viewport.setActiveItem('smsEditor', { type: 'slide', direction: 'left' });
        },
        itemTpl: '<div class="list-item-title">{title}</div>' +'<div class="list-item-narrative">{narrative}</div>',
        listeners: {'render': function (thisComponent) 
            {
                thisComponent.getStore().load();
            }
        }
    });

    SmsthingyApp.views.smsListToolbar = new Ext.Toolbar({
        id: 'smsListToolbar',
        title: 'Sent SMS',
        layout: 'hbox',
        items:[
               {xtype:'spacer'},
               {
                   id:'newSmsButton',
                   text:'New SMS',
                   ui:'action',
                   handler:function()
                   {
                       var now = new Date();
                       var smsId = now.getTime();
                       var sms = Ext.ModelMgr.create({ id: smsId, date: now, title: '', narrative: '' },'Sms');

                       SmsthingyApp.views.smsEditor.load(sms);
                       SmsthingyApp.views.viewport.setActiveItem('smsEditor', {type: 'slide', direction: 'left'});
                   }
               }
        ]
    });

    SmsthingyApp.views.smsListContainer = new Ext.Panel({
        id: 'smsListContainer',
        layout: 'fit',
        html: 'This is the sms list container',
        dockedItems: [SmsthingyApp.views.smsListToolbar],
        items: [SmsthingyApp.views.smsList]
    });

    SmsthingyApp.views.viewport = new Ext.Panel({
        fullscreen: true,
        layout: 'card',
        cardAnimation: 'slide',
        items:[
                SmsthingyApp.views.contactsListContainer,
               SmsthingyApp.views.smsListContainer,
               SmsthingyApp.views.smsEditor
               ]
    });
}

})

我使用eclipse和LogCat标签会一直标记为红色 02-08 11:11:58.741:E / Web控制台(13886):未捕获TypeError:无法读取属性&#39;联系人&#39;未定义的文件:///android_asset/www/app.js:35

我猜这有什么问题,为什么我看不到contactsListContainer中的联系人。

请帮忙吗?

1 个答案:

答案 0 :(得分:2)

我不是Sencha专家,但我确实知道这一行:

var App = new Ext.Application({

会导致PhoneGap出现问题,因为我们还声明了一个名为App的变量。最好将该行更改为:

var myApp = new Ext.Application({

避免名称冲突。

如果这不能解决您的问题,建议您阅读searching contacts上的帖子。在添加Sencha之前,我确保可以成功搜索联系人。