JSONObjects によって膨らませた ListView があります。それはうまくいっていlist.setOnItemClickListener
ます。EditText を使用して検索機能を追加し、実行時に JSONArray (JSONObjects を含む) 内の項目を検索します。しかし、検索した後、ListView 項目をクリックすると、JSONArray 内の元の位置が表示されます。たとえば、これらのアイテムの ListView があるとします。
Africa
Asia
Europe
North America
South America
[ListView の項目の位置は 0 ~ 4、つまり、アフリカ = 0、南アメリカ = 4]
ここで、検索バーに EditText フィールドを使用して入力America
すると、2 つの項目を持つリストビューが表示されます。
North America
South America
これで、実行時に ListView に 2 つの項目が表示されます。クリックするNorth America
と、JSONArray の [0] の位置が表示されます。これは元は でした。Africa
そのため、情報/データを表示する代わりに、North America
クリックしたことが表示されます。Africa
ListView Click から JSONObject を取得するにはどうすればよいですか?
/* ListView onCreate() の作成 */
public void populateCityList() {
List<CityRowItem> rowItems;
rowItems = new ArrayList<CityRowItem>();
try {
jArray = readJSONFile();
if (jArray != null) {
for (int i = 0; i < jArray.length(); i++) {
JSONObject j1 = jArray.getJSONObject(i);
CityRowItem item = new CityRowItem(R.drawable.grain,
j1.getString("city_name_eng"),
j1.getString("city_name_alias"), R.drawable.city);
rowItems.add(item);
}
CityListAdapter myadapter = new CityListAdapter(
GetCityManual.this, R.layout.list_item_city, rowItems);
list.setAdapter(null);
list.setAdapter(myadapter);
}
}
catch (JSONException) {
;
}
}
/* これは onClick リスナーです */
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
JSONObject j1 = jArray.getJSONObject(position);
String CityName = jsonObj.getString("city_name_eng");
Intent myIntent = new Intent(GetCityManual.this,
GetCategory.class);
myIntent.putExtra("objCity", CityName);
}
catch (JSONException e)
{
;
}
}
}
/* このコードは、EditText を使用した検索の機能を反映しています */
txtSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
List<CityRowItem> rowItems;
rowItems = new ArrayList<CityRowItem>();
if (jArray != null) {
try {
for (int i = 0; i < jArray.length(); i++) {
JSONObject j1 = jArray.getJSONObject(i);
if (j1.getString("city_name_eng").toLowerCase()
.contains(s.toString().toLowerCase())) {
CityRowItem item = new CityRowItem(
R.drawable.grain, j1
.getString("city_name_eng"), j1
.getString("city_name_alias"),R.drawable.city);
rowItems.add(item);
}
CityListAdapter myadapter = new CityListAdapter(
GetCityManual.this,
R.layout.list_item_city, rowItems);
list.setAdapter(null);
list.setAdapter(myadapter);
}
}
} catch (Exception _e) {
;
}
}
}