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
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
first use the models class in adapter to get and set details, and then get the data on itemclicklister like:
((DataModel)listview.getAdapter().getItem(position)).getarea_id();
Related
I have two urls, one for getting the regionname and second for login. the first url gives the response as
[{"CmpnyName":"Indore","CmpnyCode":"111"},{"CmpnyName":" Nagpur","CmpnyCode":"222"},{"CmpnyName":" Jabalpur","CmpnyCode":"333"},{"CmpnyName":"Amravati","CmpnyCode":"444"}]
now I have to display the CmpnyName in the spinner. So I did as,
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
ba = typeofcompany.getSelectedItem().toString();
SelectType(ba);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
My problem is when I select the CmpnyName, it should call its associated CmpnyCode for example indore should call 111 and so on....which is to be used in the second url...i am not getting how to do it..any help please....thank u
You can have a bean class for your model.
class MyBean implements java.io.Serializable{
String companyName;
String companyCode;
//getter-setter
}
Then set a custom adapter for your Spinner by passing array list of bean classes i.e. ArrayList<MyBean>
Then in spinner's onItemSelectedListener do something like,
typeofcompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
MyBean clickedCompany = myBeanList.get(i);
// then you can get clickedCompany.getCompanyName();
// clickedCompany.getCompanyCode();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
First, Parse your Gson string in this way:
ArrayList<HashMap<String,String>> companyNameList = new ArrayList<>()
ArrayList<HashMap<String,String>> companyIdList= new ArrayList<>();
try
{
JSONArray array = new JSONArray(preferenceManager.getSalaryJobFilter());
for(int arr = 0; arr<array.length(); arr++){
HashMap<String,String> hashMap = new HashMap<>();
HashMap<String,String> hashMap1 = new HashMap<>();
JSONObject object = array.getJSONObject(arr);
hashMap.put("companyName",object.getString("companyName"));
hashMap1.put("companyCode",object.getString("companyCode"));
companyNameList .add(hashMap);
companyIdList.add(hashMap1);
}
}
catch (JSONException e) {
e.printStackTrace();
}
Now fill your list from "companyNameList":
for (int i = 0; i < companyNameList.size(); i++) {
companyNameSpinnerList.add(companyNameList.get(i).get("companyName"));
}
companyNameAdapter.notifyDataSetChanged();
Then use
String company_name_id= companyIdList.get(i).get("companyCode");
Inside Ur "onItemSelected" method.
"company_name_id" will be the ID for the selected Company name you needed.
Method 1- Use "companyNameList" array to fill you adapter. Once you click on any item get its position and use "companyIdList" for getting id of it.
Method: 2- You can also use POJO class for it...First get the selected item position, (In ur case its "i") and use it for getting companyid from your POJO
I am create a list view using json to retrieve data from server and showing the information in list view, i try to check whether the id is successfully passed into adapter by clicking the list will showing a snackbar, but i dont know how to pass the id into list view. Here is my code.
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> adapter=new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1,players);
//ADAPT TO LISTVIEW
lv.setAdapter(adapter);
//LISTENET
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Snackbar.make(view,players.get(position),Snackbar.LENGTH_SHORT).show();
}
});
}else
{
Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
}
pd.dismiss();
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray ja=new JSONArray(data);
//CREATE JO OBJ TO HOLD A SINGLE ITEM
JSONObject jo=null;
players.clear();
//LOOP THRU ARRAY
for(int i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
//RETRIOEVE NAME
String name=jo.getString("campaign_name");
String id=jo.getString("campaign_id");
//ADD IT TO OUR ARRAYLIST
players.add(name);
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
This is the output
Create a model class Campaign with fields name and id, and override toString to return whatever you want to display in the listview ( in your case name)
Pass a list of Campaign instead of list of string in the adapter
ArrayAdapter<Campaign> adapter=new ArrayAdapter<Campaign>(..)`
In the parse method,
Campaign campaign = new Campaign()
campaign.name=jo.getString("campaign_name");
campaign.id=jo.getString("campaign_id");
players.add(campaign);`
Lastly, onItemclick
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Campaign item = parent.getAdapter().getItem(position)
Snackbar.make(view,item.id +" "+item.name,Snackbar.LENGTH_SHORT).show();
}
In same way as created players ArrayList for campaign_name, create one more ArrayList for campaign_id add store all id's in it.
In onItemClick method use campaign_id ArrayList for id of clicked item :
1. Create a ArrayList:
ArrayList<Integer> arrCampaignID=new ArrayList<Integer>();
1. Change parse() as:
String id=jo.getString("campaign_id");
//ADD IT TO OUR ARRAYLIST
players.add(name);
arrCampaignID.add(id);
2. In onItemClick use arrCampaignID to get selected campaign id:
#Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
String str_compaign_id= arrCampaignID.get(position);
}
Note , you can also do it by creating a custom class object with name and id properties, but in this case you need to create a custom Adapter by extending ArrayAdapter.
the code bellow was working so fine with me but now i don't know what's wrong with it!! whenever i click to an item it put the value of the last item to the intent! any idea?
protected void onPostExecute(List<HashMap<String, String>> result) {
customList=new ArrayList<>();
for (int i = 0; i < result.size(); i++) {
HashMap<String, String> appointement = result.get(i);
String fromT = appointement.get("fromT");
String toT = appointement.get("toT");
String date = appointement.get("date");
//int doctorid=Integer.parseInt(id.replaceAll("[\\D]",""));
addAvailableAppoint(fromT, toT, date);
}
updateListView();
}
}
private void addAvailableAppoint(final String fromT, final String toT, final String date) {
customList.add(new AvailabilityList(fromT));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("items", "fromt " + fromT + "tot: " + toT);
Intent intent = new Intent(MakeAppointementActivity.this, AppointementActivity.class);
intent.putExtra("Doctor's name", DoctorName);
intent.putExtra("Doctor's infos", DoctorInfos);
intent.putExtra("fromT", fromT);
intent.putExtra("toT", toT);
intent.putExtra("date", date);
startActivity(intent);
}
});
}
// split new function for update listview
private void updateListView(){
ArrayAdapter adapter=new DoctorAvailabilityAdapter(MakeAppointementActivity.this,R.layout.list_items,customList);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
1) You don't need to set the click listener for each new item in your list.
Just set it once, outside the for-loop.
2) Try to use a Model class for your adapter that contains all the data:
fromT , toT and date. Because as i see, your AvailabilityList contains only fromT.
3) As mentioned in #CommonsWare answer, in onItemClick try to find the appropriate object using position or id in parameters.
eg:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AvailabilityList item = (AvailabilityList)parent.getItem(position);
//Then from your item you can get the data: fromT , toT and date
}
whenever i click to an item it put the value of the last item to the intent!
You are ignoring all of the parameters to onItemClick(). If you are expecting your data to vary, you need to find the appropriate data in your collection, via position or id.
I'm having some trouble getting the correct id value when clicking on the listview.
I made a custom adapter since I'm drawing from SQLite data, I get the right text back but when I click on a row, I get a 0 index id back, which is not what I want.
I'm also using Sugar ORM, so I'm not sure if that requires some special work from me to get the id field.
I'm not sure what I should show you in terms of code, so whatever you think will help you, let me know and I'll post it.
Thanks
BoardArrayAdapter adapter = new BoardArrayAdapter(this, boards);
setListAdapter(adapter);
ListView lv = getListView();
registerForContextMenu(lv);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Board ID " + id, Toast.LENGTH_SHORT).show();
}
});
You need to override the getItemId() method in your adapter.
According to the SugarORM docs you can call getid()to return the db id.
ArrayList<Object> data;
#Override
public long getItemId(int position) {
return data.get(position).getid();
}
This is how I am using on my project (with SQLite and CustomListView).
getData method
public void getData(View view, long id)
{
//storing the ID into a public static variable and converting to int
CLIENTE_ID = (int)id;
//When the user touches on the field in the listview, I get the touched field's name and email
TextView textViewnome = (TextView) view.findViewById(R.id.tv_cliente_nome);
TextView textViewemail = (TextView) view.findViewById(R.id.tv_cliente_email);
//Stores both name and email of the touched field
String nome = textViewnome.getText().toString();
String email = textViewemail.getText().toString();
//store into static variable
CLIENTE_NOME = nome;
CLIENTE_EMAIL = email;
}
within onCreate:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
getData(view, id);
Log.d("myClass", "ID: " + view.getId());
}
});
I hope it helps! :)
I am new to Android development and I ran into a problem which I find difficult to solve. I am trying to figure out how to use an AutoCompleteTextView widget properly. I want to create a AutoCompleteTextView, using XML data from a web service. I managed to get it to work, but I am defenitely not pleased with the output.
I would like to put a HashMap with id => name pairs into the AutoCompleteTextView and get the id of the clicked item. When I click on the autocomplete filtered set output, I want to populate a list underneath the autocompletion box, which I also managed to get to work.
Done so far:
autocomplete works well for simple ArrayList, all data filtered
correct
onItemClick event fires properly after click
parent.getItemAtPosition(position) returns correct String
representation of the clicked item
The event onItemClick(AdapterView parent, View v, int position, long id) does not behave as I would like. How can I figure out the unfiltered array position of the clicked item? The position of the filtered one is the one I am not interested in.
Further questions:
How to handle HashMaps or Collections in AutoCompleteTextView
How to get the right itemId in the onItemClick event
I did very extensive research on this issue, but did not find any valuable information which would answer my questions.
The event onItemClick(AdapterView parent, View v, int position, long
id) does not behave as I would like.
This is a normal situation when filtering an adapter. Although the adapter keeps a reference to the initial unfiltered data from its point of view it has a single set of data on which is based(no matter if is the initial one or resulted from a filter operation). But this shouldn't raise any problems. With the default sdk adapters(or with a subclass), in the onItemClick() you get the position for the current list on which the adapter is based. You could then use getItem() to get data item for that position(again it doesn't matter if initial or filtered).
String data = getItem(position);
int realPosition = list.indexOf(data); // if you want to know the unfiltered position
this will work for lists and Maps(assuming that you use the SimpleAdapter). And for a Maps you always have the option of adding an additional key to set the unfiltered position in the initial list.
If you use your own adapter along with an AutoCompleteTextView you could make the onItemClick() give you the right id(the position however you can't change).
public class SpecialAutoComplete extends AutoCompleteTextView {
public SpecialAutoComplete(Context context) {
super(context);
}
#Override
public void onFilterComplete(int count) {
// this will be called when the adapter finished the filter
// operation and it notifies the AutoCompleteTextView
long[] realIds = new long[count]; // this will hold the real ids from our maps
for (int i = 0; i < count; i++) {
final HashMap<String, String> item = (HashMap<String, String>) getAdapter()
.getItem(i);
realIds[i] = Long.valueOf(item.get("id")); // get the ids from the filtered items
}
// update the adapter with the real ids so it has the proper data
((SimpleAdapterExtension) getAdapter()).setRealIds(realIds);
super.onFilterComplete(count);
}
}
and the adapter:
public class SimpleAdapterExtension extends SimpleAdapter {
private List<? extends Map<String, String>> mData;
private long[] mCurrentIds;
public SimpleAdapterExtension(Context context,
List<? extends Map<String, String>> data, int resource,
String[] from, int[] to) {
super(context, data, resource, from, to);
mData = data;
}
#Override
public long getItemId(int position) {
// this will be used to get the id provided to the onItemClick callback
return mCurrentIds[position];
}
#Override
public boolean hasStableIds() {
return true;
}
public void setRealIds(long[] realIds) {
mCurrentIds = realIds;
}
}
If you also implement the Filter class for the adapter then you could get the ids from there without the need to override the AutoCompleTextView class.
Using the Luksprog approach, I made some similar with ArrayAdapter.
public class SimpleAutoCompleteAdapter extends ArrayAdapter<String>{
private String[] mData;
private int[] mCurrentIds;
public SimpleAutoCompleteAdapter(Context context, int textViewResourceId,
String[] objects) {
super(context, textViewResourceId, objects);
mData=objects;
}
#Override
public long getItemId(int position) {
String data = getItem(position);
int index = Arrays.asList(mData).indexOf(data);
/*
* Atention , if your list has more that one same String , you have to improve here
*/
// this will be used to get the id provided to the onItemClick callback
if (index>0)
return (long)mCurrentIds[index];
else return 0;
}
#Override
public boolean hasStableIds() {
return true;
}
public void setRealIds(int[] realIds) {
mCurrentIds = realIds;
}
}
Implement onItemClickListener for AutoCompleteTextView, then use indexOf on your list to find the index of selected item.
actvCity.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int index = cityNames.indexOf(actvCity.getText().toString());
// Do Whatever you want to do ;)
}
});
First add your data into custom arraylist
// mList used for adding custom data into your model
private List<OutletListSRModel> mList = new ArrayList<>();
// listdata used for adding string data for auto completing.
ArrayList<String> listdata = new ArrayList<String>();
for (int i = 0; i < JArray.length(); i++) {
JSONObject responseJson = JArray.getJSONObject(i);
OutletListSRModel mModel = new OutletListSRModel();
mModel.setId(responseJson.getString("id"));
mModel.name(responseJson.getString("outlet_name"));
listdata.add(responseJson.getString("outlet_name"));
}
ArrayAdapter adapter = new
ArrayAdapter(getActivity(),
android.R.layout.simple_list_item_1, listdata);
searchOutletKey.setAdapter(adapter);
Now for getting any value from model which we added above. we can get like this.
searchOutletKey.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String txtOutletId = mOutletListSRModel.get(position).getId();
}
});