我做了一個活動,獲取jsonarray並將其放入列表中。接下來,我將一個AutoCompleteTextView分配給一個字段女巫,用於捕捉我使用的json對象。Json解析自動完成
在我的jsonarray其3個對象:ItemID,ItemDescription和ItemVolume。我的AutoCompleteTextView字段包含jsonObject:ItemDescription。
當我在onItemClickListner中選擇itemDescription時,我需要獲取itemID。
繼承人的代碼
ArrayAdapter<String> adp = new ArrayAdapter<String>(shoppingcart.this,
android.R.layout.simple_dropdown_item_1line, responseList);
autocomplete.setAdapter(adp);
autocomplete.setThreshold(1);
private class GetContacts extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(shoppingcart.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(urlget);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
autocomplete.setThreshold(1);
try {
// Getting JSON Array from URL
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getString(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getString(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
編輯:
這是我所做的零部件清單。
HashMap<String,Integer> ItemAndID= new HashMap<String,Integer>();
List<String> responseList = new ArrayList<String>();
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
AllItems = json.getJSONArray(TAG_GETALL);
for(int i = 0; i < AllItems.length(); i++) {
JSONObject c = AllItems.getJSONObject(i);
// Storing JSON item in a Variable
ID = c.getInt(TAG_ID);
Name = c.getString(TAG_NAME);
Pris = c.getInt(TAG_PRICE);
// Adding value HashMap key => value
responseList.add(Name);
ItemAndID.put(Name, ID);
}
對於的OnClick我這樣做。
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedName = (String) parent.getItemAtPosition(position);
// if you used a HashMap
ResultID = ItemAndID.get(selectedName);
}
偉大的回答,請參閱我的文章的結果。 – Jack
謝謝!偉大的:) –