10 points
Code.org makes available various datasets that can be used in apps. To view the datasets, click on the Data option at the upper-left of the screen. In this app, you access a table (or database) called "RollingStone: 500 Albums" in "Culture and Entertainment." If you click on "RollingStone: 500 Albums" you'll see the buttons "Preview" and "Import." If you click "Preview," you'll see that each row of the table has information on an album. The columns of the table ("id", "Album Rank," "Year", "Artist" etc.) store relevant information on the album. You should click "Import," which will allow the app to access the table.
Each row in a table is called a "record." You can use the readRecords() function to read the rows (records) in the table into the app. An example of this is given below. The name of the table "RollingStone: 500 Albums" is the first parameter of readRecords(). A filter that specifies which columns to use in pulling records from the table is next. In the example below, this is {Artist:"The Beatles"}. The effect of this filter is that only albums by the Beatles will be pulled from the table. The records that readRecords() pulls from the table are stored in the list "records". What follows is "function(records){ }" which processes the records that have been pulled from the table.
readRecords("RollingStone: 500 Albums", {Artist:"The Beatles"}, function(records)
{ .....
.....
});
It would be more useful if readRecords() could pull records for any artist. This can be done by using a variable "artist." Then the filter sent to readRecords() becomes {Artist:artist}:
readRecords("RollingStone: 500 Albums", {Artist:artist}, function(records)
{ .....
.....
});
In the app, set up a Text Input and a Label. The user types an artist's name in the box and clicks the button. 'getText()' then assigns the artist's name to the variable 'artist'. A loop inside "function(records") processes the records stored in 'records.' The number of entries in the list 'records' is given by 'records.length'. "records[k]" holds one row of the table, and "records[k].id" gives the id, "records[k].Artist" gives the artist, and "records[k].Album" gives the album name.
Here's an outline of the structure of the app:
- set up an onEvent that runs when the button is clicked
- read the artist's name from the Text Input
- start the readRecords() function
- set up a loop that runs 'records.length' times
- inside the loop, add the album's id and name to a cumulative string: output = output + ...
- end the loop
- use setText() to print the cumulative string in a Label
- end the readRecords() function
Here is some documentation:
The video shows what a completed app should do.