获取基于数据库android的精选微调器数据的id

时间:2016-07-18 05:49:50

标签: android sqlite android-sqlite

嗨我有这个微调器下拉列表,显示我数据库中的数据。在我的数据库中,我有一个名为area的表,它有这个字段,aid是主键,location是varchar。到目前为止,我成功地在我的微调器中显示数据。在我的DBHelper中,这是从DB

获取数据的代码
public Set<String> getAllData()
{
    Set<String> set = new HashSet<String>();
    String selectQuery = "SELECT * FROM " + TABLE_AREA;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            set.add(cursor.getString(1));
        } while (cursor.moveToNext());
    }
    db.close();
    return set;
}

然后在我的addLocation.java中,这是我如何使用它来显示我的微调器上的数据

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.addplace);
    Spinner spn = (Spinner)findViewById(R.id.areas);

    Set<String> aset = db.getAllData();
    List<String> aData = new ArrayList<>(aset);
    ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item,
            aData);
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spn.setAdapter(spinnerAdapter);
    spn.setOnItemSelectedListener(new SpinnerInfo());
}

private class SpinnerInfo implements AdapterView.OnItemSelectedListener {
    private boolean isFirst = true;
    String selected;
    @Override
    public void onItemSelected(AdapterView<?> spinner, View selectedView, int selectedIndex, long id)
    {
        if (isFirst)
        {
            isFirst = false;
        }
        else
        {
            String selection = spinner.getItemAtPosition(selectedIndex).toString();
            selected = selection;
        }
        Toast tempMessage =
                Toast.makeText(addLocation.this,
                        selected,
                        Toast.LENGTH_SHORT);
        tempMessage.show();
    }
    @Override
    public void onNothingSelected(AdapterView<?> spinner) {
    // Won’t be invoked unless you programmatically remove entries
    }
}

问题是我需要获取所选位置的id而不是微调器中的索引,但它是数据库ID。我怎么能这样做的任何想法?非常感谢!

1 个答案:

答案 0 :(得分:-1)

  

我需要获取所选位置的ID而不是索引   微调器,但它的数据库ID。我怎么能这样做?

使用HashMap执行:

1。使用HashMap代替Set,其中location为关键,位置ID为value。更改getAllData()

public Map<String, Integer> getAllData()
{
    Map<String, Integer> hashMap = new HashMap<String, Integer>();
     ...
    if (cursor.moveToFirst()) {
        do {
            hashMap.put(cursor.getString(1),cursor.getString(0));
        } while (cursor.moveToNext());
    }
    db.close();
    return hashMap;
}

2. 将所有密钥传递给Spinner:

  Map<String, Integer> hashMap = db.getAllData();
  List<String> allLocations = new ArrayList<String>(hashMap.keySet());

3。现在在onItemSelected中使用selected字符串获取所选项目的ID:

int location_id=hashMap.get(selected);