gpt4 book ai didi

java - 如何使用微调器进行改造来检索 2 个值

转载 作者:行者123 更新时间:2023-11-29 22:38:20 26 4
gpt4 key购买 nike

我有这样的代码 JSON,我希望当我选择微调器 selecteditem 的值为 Baru 时,它会显示在 Toast Baru 的 ID 中。

JSON:

1

到目前为止,我已经尝试从 JSON 中显示 Baru 的 ID:

spinnerProvinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int IDProvinces = getProvincesIDList.get(i - 1);
Toast.makeText(getContext(), "ID Province : " + IDProvinces, Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

有回应:

private void fetchProvinces(int country_id) {
Call<JsonObject> getProvinces = baseApiService.getProvinces(country_id);
getProvinces.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
if (!response.isSuccessful()) {
Log.e(TAG, "Request Error : " + response.code());
} else {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("data");
modelGetProvincesList = new ArrayList<>();
getProvincesIDList = new ArrayList<>();

for (int a = 0; a < jsonArray.length(); a++) {
objectProvinces = jsonArray.getJSONObject(a);
getIDProvinces = objectProvinces.getInt("id");
modelGetProvincesList.add(objectProvinces.getString("name"));
getProvincesIDList.add(getIDProvinces);
}

ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, modelGetProvincesList);
spinnerProvinsi.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}

@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(TAG, "onFailure : " + t.getMessage());
}
});
}

当我调试时,错误出现在 logcat 中:

java.lang.ArrayIndexOutOfBoundsException: length=49; index=-1
at java.util.ArrayList.get(ArrayList.java:439)
at com.product.shopciety.ui.menu.menu_signin.menu.MenuTambahAlamatFragment$2$1.onItemSelected(MenuTambahAlamatFragment.java:128)

最佳答案

不要提供i-1。您的索引也从 0 开始,但是当您尝试选择 baru 时,它占据位置 0 - 1 = -1。所以只需提供 i,它是 ArrayList 中 baru 的索引。

spinnerProvinsi.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int IDProvinces = getProvincesIDList.get(i);
Toast.makeText(getContext(), "ID Province : " + IDProvinces, Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

关于java - 如何使用微调器进行改造来检索 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59301770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com