我从Web服务中拥有此json
:
[{"id_mata_kul":"2","mata_kul":"Oracle Database"},{"id_mata_kul":"3","mata_kul":"Pengatar Manajemen dan Bisnis"},{"id_mata_kul":"5","mata_kul":"Leadership"}]
然后我可以在旋转器中显示mata_kul
对象,但是我需要从mata_kul
获取ID而不显示ID中的旋转器,
问题:
我需要保存所选mata_kul
的ID依赖。
在示例中:当从旋转器中选择Leadership
时,我需要使用意图保存该id 5
。以及另一个,当从旋转器中选择Oracle Database
时,我需要使用意图保存id 2
,
我已经阅读了与我相同问题的帖子,但我不知道它是如何工作的,
有人可以帮助我如何解决这个问题吗?
编辑:
在doInBackground
中:
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
list2.add(jsonObject.getString("mata_kul")); //collecting all json `mata_kul`
}
在onPostExecute
中:
listItems2.addAll(list2);
adapter2.notifyDataSetChanged();
在onCreate
中:
adapter2= new ArrayAdapter<>(this, R.layout.spinner_layout, R.id.txt, listItems2);
尝试以这种方式获取ID
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtrank = (TextView) findViewById(R.id.rank);
TextView txtcountry = (TextView) findViewById(R.id.country);
TextView txtpopulation = (TextView) findViewById(R.id.population);
// Set the text followed by the position
txtrank.setText("Rank : "
+ world.get(position).getRank());
txtcountry.setText("Country : "
+ world.get(position).getCountry());
txtpopulation.setText("Population : "
+ world.get(position).getPopulation());
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
http://www.androidbegin.com/tutorial/android-populating-spinner-json-tutorial/
您可以使用hashmap解决问题。将您的ID值存储为键,将MATA_KUL零件作为hashmap中的值存储为值。然后使用hashmap值以在旋转器中显示。单击项目时,使用该值从Hashmap中查找相应的ID。
覆盖旋转器OnItemClickListener并获得所选项目位置
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
int selectedItemPos = position;
//use selectedItemPos to retrieve id values from json array
}
首先,创建一个模型以从Web服务存储JSON值。然后使用此模型创建自定义适配器。并处理Spinner的项目选定事件:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Model model = (Model) parent.getItemAtPosition(position);
// do something with the model
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}});