有人知道从spinner获取索引id值,我有这个代码,但它是错误的 Akreditasi.java
public class Akreditasi {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return nama;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString()
{
return "ID : " + id
+ "\n" + "Nama :"+ name;
}
}
这是mySpinner 我正在尝试将此Akreditasi传递给ArrayAdapter
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id)
{
// TODO Auto-generated method stub
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
Akreditasi mSelected = (Akreditasi) parent.getItemAtPosition(position); //in here my program is crash, it's says cannot be cast
long count = mSelected.getId();
//set the default according to value
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You Selected: " + label,
Toast.LENGTH_LONG).show();
}
这是我的微调方法
private void loadSpinnerData() {
// TODO Auto-generated method stub
// database handler
DBDataSource db = new DBDataSource(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllLabel_akreditasi();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
我仍然不明白这个错误,任何人都可以帮助我吗?谢谢你
答案 0 :(得分:1)
因为你没有告诉你将使用哪种微调器,
首先,您需要调用onItemSelected
方法,如下所示:
(your spinner).setOnItemSelectedListener(this);
在此之后,我建议您在方法switch case
上添加onItemSelected
,如下所示:
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id)
{
switch (parent.getId()) {
case R.id.(id of your spinner):
Akreditasi mSelected = (Akreditasi) parent.getItemAtPosition(position);
long count = mSelected.getId();
break;
}
}
你的微调方法应该是这样的:
private void loadSpinnerData() {
DBDataSource db = new DBDataSource(getApplicationContext());
List<Akreditasi> lables = db.getAllLabel_akreditasi();
ArrayAdapter<Akreditasi> dataAdapter = new ArrayAdapter<Akreditasi>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
答案 1 :(得分:0)
在设置设置时,您只有List<String>
但不是List<Akreditasi>
List<String> lables = db.getAllLabel_akreditasi();
你需要一个逻辑来为示例代码设置对象
Akreditasi [] items = {
new Akreditasi (1, "Milk", 21.50),
new Akreditasi (2, "Butter", 15.99),
new Akreditasi (3, "Yogurt", 14.90),
new Akreditasi (4, "Toothpaste", 7.99),
new Akreditasi (5, "Ice Cream", 10.00),
};
ArrayAdapter<Product> adapter = new ArrayAdapter<Product>(this,
android.R.layout.simple_list_item_1, items);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);