How to retrive values from Database in Titanium Al

2019-06-03 17:02发布

问题:

I'm new to Titanium API. I want to know how to retrieve values from DB and display in UI. I created a model and inserted a row. My code is as below,

Model:

var moment = require('alloy/moment');

exports.definition = {
    config : {
            "columns": {
            "id":"text",
            "LanguageName":"text"
            },
            "adapter": {
                "type": "sql",
                "collection_name": "UserLanguage"
            }
    },

    extendModel: function(Model) {      
        _.extend(Model.prototype, {

        });

        return Model;
    },

    extendCollection: function(Collection) {        
        _.extend(Collection.prototype, {

        });

        return Collection;
    }
};

View:

<Alloy>
    <Window id="changeLangWindow" title="Plan India">
        <Picker id="langPicker">
            <PickerRow title="Select a Language"/>
            <PickerRow title="English"/>
            <PickerRow title="French"/>
            <PickerRow title="Spanish"/>
        </Picker>
        <Button class="button" onClick="saveLang">Proceed</Button>
        <Label class="question">Selected Language is: -------</Label>
    </Window>
</Alloy>

Controller:

function saveLang() {

    var UserLang = Alloy.Collections.UserLanguage;

    // Create a new model for the todo collection
    var task = Alloy.createModel('UserLanguage', {
        id : '1',
        LanguageName : 'English'
    });

    // add new model to the global collection
      UserLang.add(task);

    // save the model to persistent storage
    task.save();

    // reload the tasks
     UserLang.fetch();

}

I want to select the value of "LanguageName" from "UserLanguage" model and display in the View that is in XML file.

Any suggestions with explanation please!

回答1:

// Try this code May be this is helpful for you.

if (Alloy.Collections.UserLanguage.length) {
     Alloy.Collections.UserLanguage.map(function(obj) {

        Ti.API.Log(" LanguageName "+ obj.get('LanguageName'));
        Ti.API.Log(" LanguageName "+ obj.id);

     });

}

Thanks,