How to pull data from database and store them into arrays in Android?
I am learning Android development. I have an IOU table that has name and amount. So, after multiple entries into the DB table, you would have something like this:
name1 50
name2 25
name1 10
name3 60
... ...
My question is, what is the best way to pull the entries from the table and sort them as an array in an Adroid application.
For example, Array1[] name1 = [50, 10, ...] where 50 and 10 are the amount associated with name1 in the DB.
I cannot just use SELECT * FROM table WHERE name = name1
because the names will change and it will be increasing. I heard from this SO question:
How to store arrays in a database?
that dynamically 开发者_运维技巧generating table is not a good idea.
I think you want a query like this:
SELECT * FROM table ORDER BY name
or
SELECT * FROM table ORDER BY amount
That is, you don't need a WHERE clause if you want all of the rows. And the ORDER BY clause can do the sorting for you.
However: Are you sure that you need to pull all the data into an array -- especially if the database can do the sorting that you need? One alternative would be to open a cursor, and then do whatever processing you need one row at a time.
EDIT: Another example (based on your comment; I have not tested this):
SELECT name, SUM(amount) FROM table GROUP BY name ORDER BY name
will give you one row for each unique name in the database, with the sum of each amount associated with that user. For the example you posted above, this would result in the following rows:
name1 60 // The sum of the two rows that have name="name1"
name2 25
name3 60
精彩评论