简体   繁体   English

基于rowId的Spinner上的setSelection

[英]setSelection on Spinner based on rowId

I have a Spinner View that's populated through a SimpleCursorAdapter. 我有一个Spinner视图,它通过SimpleCursorAdapter填充。

Based on the selection I need to save the rowid in the entry database (position won't work because things can be added and deleted from the Spinner Database). 根据选择我需要将rowid保存在条目数据库中(位置不起作用,因为可以从Spinner数据库中添加和删除内容)。

This I can do by using spinner.getAdapter().getItemId(pos); 我可以使用spinner.getAdapter().getItemId(pos); . But When I edit an entry I need to make the Spinner position selected that is associated with this rowid (currently). 但是当我编辑一个条目时,我需要选择与此rowid相关联的Spinner位置(当前)。

spinner.setSelection(position); won't work because I have the rowid, I need a way to find the current position of the item in the current spinner based on the rowid in the database. 因为我有rowid,所以无法工作,我需要一种方法来根据数据库中的rowid查找当前微调器中项目的当前位置。

If you want to set the selection of a Spinner thats backed by a CursorAdapter , you can loop through all the items in the Cursor and look for the one you want (assuming that the primary key in your table is named "_id"): 如果要设置由CursorAdapter支持的Spinner的选择,可以循环遍历Cursor中的所有项目并查找所需的项目(假设表中的主键名为“_id”):

Spinner spinner = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(new SimpleCursorAdapter(...));

for (int i = 0; i < spinner.getCount(); i++) {
    Cursor value = (Cursor) spinner.getItemAtPosition(i);
    long id = value.getLong(value.getColumnIndex("_id"));
    if (id == rowid) {
        spinner.setSelection(i);
    }
}

If you want to get the rowid of a selected item, you can do something similar: 如果你想获得所选项目的rowid,你可以做类似的事情:

Cursor cursor = (Cursor) spinner.getSelectedItem();
long rowid = cursor.getLong(cursor.getColumnIndex("_id"));

There might be a quicker way to do it, but that's always worked for me. 可能有更快的方法,但这对我来说总是有用。

I agree with Erich Douglass's above answer but i found fastest loop syntax which will be useful while spinner.getCount() is greater than 50k to 100k . 我同意Erich Douglass的上述答案,但我找到了最快的循环语法,当spinner.getCount()大于50k到100k时,它会很有用。

/* 1 (fastest) */
for (int i = initializer; i >= 0; i--) { ... }

/* 2 */
int limit = calculateLoopLimit();
for (int i = 0; i < limit; i++) { ... }

/* 3 */
Type[] array = getMyArray();
for (Type obj : array) { ... }

/* 4 */
for (int i = 0; i < array.length; i++) { ... }

/* 5 */
for (int i = 0; i < this.var; i++) { ... }

/* 6 */
for (int i = 0; i < obj.size(); i++) { ... }

/* 7 (slowest) */
Iterable<Type> list = getMyList();
for (Type obj : list) { ... }

So i think we can use here second for better performance: 所以我认为我们可以在这里使用第二个更好的性能:

int spinnerCount = spinner.getCount();
for (int i = 0; i < spinnerCount; i++) {
    Cursor value = (Cursor) spinner.getItemAtPosition(i);
    long id = value.getLong(value.getColumnIndex("_id"));
    if (id == rowid) {
        spinner.setSelection(i);
    }
}

Had an idea when writing this, made a hashtable with rowid->pos when populating the spinner and then used that. 写这篇文章时有一个想法,在填充微调器时使用rowid-> pos创建一个哈希表,然后使用它。 Might help someone if they're searching. 如果他们正在搜索,可能会帮助某人。

I think that instead of a for loop is better a while, because when you find your item, can break the loop. 我认为代替for循环会更好一段时间,因为当你找到你的项目时,可以打破循环。

int spinnerCount = spinner.getCount();
int i = 0;
while(i++ < spinnerCount) {
    Cursor value = (Cursor) spinner.getItemAtPosition(i);
    long id = value.getLong(value.getColumnIndex("_id"));
    if (id == rowid) {
        spinner.setSelection(i);
        break;
    }
}

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: 要通过id获得位置:

SELECT * FROM my_view2 WHERE _id=11

Results: 结果:

row_id | _id | field

5   11  EQQwPKksIj

Hope that help 希望有所帮助

https://stackoverflow.com/a/5040748/1206052 https://stackoverflow.com/a/5040748/1206052

dziobas dziobas

has provided an awesome answer.. But I am not surprised why nobody has recommended it.. just want to make some correction in his answer.. 提供了一个很棒的答案..但我并不感到惊讶,为什么没有人推荐它..只是想在他的答案中做出一些修正..

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

I just replaced "where" with "on" that is required by join.. 我只是将“where”替换为join所需的“on”。

now u have all the items with their Positions associated with there ID's.. 现在你有所有与他们的职位相关联的项目ID。

Just assign the ROW_id to the setselection() of spinner 只需将ROW_id分配给微调器的setselection()

Why do it the hard way when you can do it the right way? 为什么你能以正确的方式做到这一点很难?

I refer to the manual: 我参考手册:

http://d.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29 http://d.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29

example code: 示例代码:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            int index = spinner.getSelectedItemPosition();
            Toast.makeText(getBaseContext(), 
                "You have selected item : " + index + " which is row " + id, 
                Toast.LENGTH_SHORT).show();                
        }
        public void onNothingSelected(AdapterView<?> arg0) {}
    });

Thanks to evancharlton on #android-dev for this enlightment. 感谢#android-dev上的evancharlton为此启发。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM