1

I'm building a list that is sorted alphabetically. The list should show a divider containing the Letter that the following icons belong to.

I'm using a Cursoradapter that contains the already sorted result from the database. I plan on adding the divider to the list item and set it to visible if the shown letter changes. How do I know that I have a new Letter? Is there a better way then going forward or backward in the cursor and check if the item I show is the end or beginning of a new group?

1 Answer 1

2

You can do that in SQL query that provides data for Cursor.

Suppose we have person(name varchar) table.

Instead of asking just:

SELECT name FROM person ORDER BY name;

one can query:

SELECT p.name, CASE(
    SELECT COUNT(*) 
    FROM person 
    WHERE name<p.name and SUBSTR(name, 1, 1)=SUBSTR(p.name,1 , 1)
    ) WHEN 0 THEN 1 ELSE 0 END isFirst 
FROM person p 
ORDER BY name;

that gives (name, isFirst) resultset - each item starting with "new" letter will have isFirst set to 1 indicating start of new group.

edit: Example:

CREATE TABLE person(name varchar);
INSERT INTO person SELECT 'Jim' UNION SELECT 'Tom' UNION SELECT 'Ben' UNION SELECT 'John' UNION SELECT 'Alice' UNION SELECT 'Chris' UNION SELECT 'Anna' UNION SELECT 'Jerry';
SELECT p.name, CASE(
    SELECT COUNT(*) 
    FROM person 
    WHERE name<p.name and SUBSTR(name, 1, 1)=SUBSTR(p.name,1 , 1)
    ) WHEN 0 THEN 1 ELSE 0 END isFirst 
FROM person p 
ORDER BY name;

gives:

Alice|1
Anna|0
Ben|1
Chris|1
Jerry|1
Jim|0
John|0
Tom|1
3
  • Great idea but the sample is not working. substring(name) and substring(p.name) are always the same
    – Janusz
    Jun 24, 2010 at 9:51
  • Thanks for the example it is working now i overlooked the person p thing at the end.
    – Janusz
    Jun 24, 2010 at 10:19
  • By the way you can Re-tag question adding 'sql' and 'sqlite' tags.
    – Gawcio
    Jun 24, 2010 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.