2017년 7월 30일 일요일

File component and CSV files


There have been a few questions about making a "question and answer" app or something similar that has a table in it. 
I wanted to make  simple .csv file, load the file into an app, and read it into a list of lists. It drove me almost nuts before I finally figured it out, thanks to several examples, most notable one from Taifun (which I cannot find back right now to link to it).

Here goes:
We have a .csv file which looks like this: 
T1. Question one, one|T1. Answer one, two
T1. Question two, one|T1. Answer two, two
As you can see, the fields are delimited by | (a pipe) and not by , (a comma). This is handy, because it allows us more freedom in creating text. It would be very limiting if we would have to write questions and answers as sentences without comma's! If it is small, you can create such a file using a simple text editor, otherwise use some spreadsheet program. I found that using Excel is not very easy, because it is difficult to tell Excel to use | or anything else as ; for that matter as delimiter. Open Office, or Libre Office (both free) are much easier to use for this purpose.

In our example app, we made a design like this: 

It just allows us to check whether our blocks are right. We upload the .csv file into the app as T1.csv

during initialize we read T1.csv as follows: 

In this example the file is an asset in the app. If the file is very big, it would be better to have it stored somewhere on your sdcard. For example, a filename /qa/T1.csv would locate the same file in a folder qa on the card. The advantage of such an approach is that it would be possible to distribute a new file without distributing a new app, but it would not be easy for many users to place the file on their phones in the right spot.

When the file is read, a GotText event will be raised:
Unfortunately, we cannot use list from csv table, because we do not have , (comma) as delimiter. (How nice would it be if we could specify what the delimiter is!)
Therefore we split the text we just read first into a list of rows, and next we split each row into a list of elements.
To check if we did everything right, our example app has two listviews, to display the two rows of our example .csv file:
 and that shows on our telephone screen: 


After having read the elements as a list of lists into the global Topic1 in our example, you could expand this by storing the list in a TinyDB, (which would actually not be necessary if you were reading the file always at app startup, unless you would be using multiple screens).
You can use the attached .aia to try things out.


--

댓글 없음:

댓글 쓰기