How to load a ListView using SQLite in Titanium? How to load a ListView using SQLite in Titanium? sqlite sqlite

How to load a ListView using SQLite in Titanium?


This isn't written for Alloy, but it's plug-and-play code.

// Create main windowvar win = Ti.UI.createWindow({    backgroundColor:"#bbb",    navBarHidden : true,    orientationModes : [Titanium.UI.PORTRAIT]});// Install the databasevar db = Ti.Database.install("myDB.sqlite", "myDB");db.close();// Create the empty arrayvar myBooks = [];// Set data in the appfunction setData(){    var db = Ti.Database.open("myDB");    // Select the "books" table in the database    var rows = db.execute("SELECT * FROM books");    while (rows.isValidRow()) {    // Add each "title" under the books table to the array    myBooks.push(rows.fieldByName("title"));    rows.next();    }    rows.close();    db.close();    // Print the array    Ti.API.info(myBooks);}// call the functionsetData();win.open();

I just made a simple database in sqlite with one table "books", and then "titles" under books. Within "books" I added three values, "Book One", "Book Two" and "Book Three".

From here you should be able to use the myBooks array to add to your ListView in Alloy.


I found the answer, It is not necessary to parse the value to an array and call the line:

$.elementsOnList.section[0].setItems(books);

Intead of you can simply:

//Get a reference to our collection:Alloy.Collections.books.fetch();

And in the view .js make use of the properties that offer Titanium through its framework Alloy:

<Alloy>  <Collection src="books" />    <Window>    <ListView defaultItemTemplate="by_name">      <Templates>        <ItemTemplate name="by_name">          <View>            <Label bindId="title"/>          </View>        </ItemTemplate>      </Templates>      <ListSection dataCollection="books">        <ListItem title:text="{title}" />      </ListSection>    </ListView>    </Window></Alloy>

And with that few lines of code my list is loading data from the database.