How can I get the position of a row in a dataset in order to set the selected item in an Android Spinner?

心已入冬 提交于 2019-12-08 01:32:35

问题


I have a Spinner that's populated using a cursor containing data from a database. It appears that it's impossible to set the selected item in the spinner using the value of the ID column of a row. And that the only way to set the selected item is by using the position of the row within the dataset. Is this correct? If so, is there a more efficient way of determining the row's position than by iterating through the dataset using the cursor?

The inefficient (to my mind) way is outlined here.

Thanks much!


回答1:


First step, create view for your data set, with joins etc.:

CREATE VIEW my_view AS
  SELECT _id, field FROM my_table

Second step:

CREATE VIEW my_view2 AS
  SELECT count(*) AS row_id, q1.*
  FROM my_view AS q1
  LEFT JOIN my_view AS q2
  WHERE q1._id >= q2._id
  GROUP BY q1._id

Then simply:

SELECT * FROM my_view2

Results:

row_id | _id | field

1   4   XbMCmUBFwb
2   6   Te JMejSaK
3   8   dDGMMiuRuh
4   10  phALAbnq c
5   11  EQQwPKksIj
6   12  PAt tbDnf
7   13  f zUSuhvM
8   14  TIMBgAGhkT
9   15  OOcnjKLLER

To get position by id:

SELECT * FROM my_view2 WHERE _id=11

Results:

row_id | _id | field

5   11  EQQwPKksIj

Hope that help



来源:https://stackoverflow.com/questions/5026646/how-can-i-get-the-position-of-a-row-in-a-dataset-in-order-to-set-the-selected-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!