Oreo Oreo - 3 months ago 13
JSON Question

AutoCompleteTextView get value from ArrayList based on Position

I am using

AutoCompleteTextView
in my program, where I am showing suggestions from JSON and my JSON looks like:

{"areas":[{"area_id":"1","area_name":"Area 1"},{"area_id":"2","area_name":"Area 2"}],"success":1}


Here is the AutoCompleteTextView code along with
OnItemClick
:

textArea.setAdapter(stringArrayAdapterAreas);

textArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

// along with name, I also want to fetch Id of that particular area

autoAreaName = (String) parent.getItemAtPosition(position);
Log.d("AreaName:", autoAreaName); // getting accurate area name

if(areaArrayList.contains(autoAreaName)) {

// how to get area id using area name

}

}
});


Code to fetch available
Areas
, from webservice:

if (success == 1) {
JSONArray jsonArray = response.getJSONArray("areas");

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);

Area area = new Area();
area.setId(jsonObject.getInt("area_id"));
area.setName(jsonObject.getString("area_name"));

// adding area to areas array
stringArrayListAreas.add(jsonObject.getString("area_name"));

areaArrayList.add(area);

} // for loop ends


} // if ends


What is the best way to get both the values (Area Id and Name) from JSON ?

UPDATED

public String toString(){
return id+":"+name;
}


Activity

textArea.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

Area area = new Area();
Log.d("areaData:", area.toString());

}
});


Lag says

D/areaData:: 0:null

Answer

What is the best way to get both the values (Area Id and Name) from JSON ?

the best way is to bind the adapter you are feeding to the AutoCompleteTextView with a model class that contains both info. E.g.

 public class Model {
   public String name;
   public String area_id;

   public void toString() {
      return name;
   } 
 }

you will have to change your code to use this class. In Your onItemClick you will cast to Model instead of String, and access its members to extract the information you need

Comments