my spinner and how to get the position of item selected - android

i have a spinner populated by an arraylist with multiple hashmaps at each index for each "rung" on the spinner. So when the item is selected, i want to get the single key that is selected and do something with it
i do like this in my pic but there is a problem
how can i solve it
image http://www.qzal.net/01/2012-10/13530999521.png
Here is a usable copy of the code:
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();
// for each key in the hashMap at this position..
for (String key : arrList.get(position).get("SectionID"))
{
}
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});

You must do this one level at a time. First fetch each HashMap from your ArrayList, then ask for your specific key:
for (HashMap<String, String> map : arrList) {
String value = map.get("SectionID");
// Do something
}
However if you just initialized arrList there won't be anything in it...

Related

how to get Associated Json value based on selected spinner item

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

How to pass id to other activity if my list view is created by JSON objects when clicked

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.

spinner and onItemSelected

If I have 2 spinner depended with type ArrayList>
spinner2.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();
for (HashMap<String, String> map2 : arrList) {
String value = map2.get("SectionID");
// Do something
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, value, duration);
toast.show();
Log.d("wwwwwwwwwwwwwwwwwwww: ", value);
// Do something
}
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {
}
});
i do like this but kothing happend and logcat not having error
I do not know how to get the item with tag (courseid) in this array after the user click the item in spinner.
If you only want to get the courseid from each row, you do not need a custom OnItemSelectedListener. Simple use:
// Let's use the regular listener vvvvvvvvvvvvvvvvvvvvvv
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
HashMap<String, String> map = arrList.get(position);
String id = map.get("courseid");
// Do something
}
#Override
public void onNothingSelected(AdapterView<?> adapter) {}
});
Where arrList is the class variable that holds the data for your SimpleAdapter.
i do like this but kothing happend and logcat not having error
That is because you just created arrList, so it is empty:
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();
for (HashMap<String, String> map2 : arrList) { // This arrList has no data!
You need to use the ArrayList that you used when you created your SimpleAdapter.
new SimpleAdapter(this, arrList, ...);
This is the ArrayList you must use and it must be a class variable.
Your post is a little hard to understand, but i think i have an idea. you have a single spinner populated by an arraylist with multiple hashmaps at each index for each "rung" on the spinner. So when the item is selected, you want to get the single key that is selected and do something with it. Well as we know, a hashMap isn't really indexed so we have to use alternative methods to get at it, correct?
ArrayList<HashMap<String, String>> arrList = new ArrayList<HashMap<String,String>>();
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// for each key in the hashMap at this position..
for (String key : arrList.get(position).keySet()) {
if (key == "Calculus") {
// do something
} else if (key == "Physics") {
// do something else
}
}
}
The idea is really simple here. you get the entire keySet of the hashMap at the index of the position selected on the spinner and you do something for each key in it, depending on what it says. This should work without too much hassle, assuming you only have one key-value pair there.
BUT I have to say that you should really re-think the design a bit. You have multiple hashMap containers just holding one thing each. It really is a waste of resources. it's hard to recommend an alternative because i don't exactly know how this data is being used, but you should know that making objects in java isn't free.

How to get correct ID of AutoCompleteTextView adapter

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();
}
});

How to sort HashMap as added in Android with ArrayAdapter

I have a HashMap<String,String> and there is a static method which returns this map to an Activity.
Method looks like this:
public static HashMap<String, String> getAll() {
HashMap<String, String> map = new HashMap<String,String>();
map.put("ab", "value1");
map.put("bc", "value2");
map.put("de", "value3");
return map;
}
I want to use that map with a spinner. So activity looks like this:
List list = new ArrayList<String>();
HashMap<String, String> map = Constants.getAll();
for (String key : map.keySet()) {
list.add(Constants.getAll().get(key).toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinTest = (Spinner)findViewById(R.id.spinTest);
spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
urlDebug.setText(list.get(arg2).toString());
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinTest.setAdapter(adapter);
When I tried to run my application, no problem at all. But when I clicked on spinner, items not ordered as I added on getAll() method. I mean, order has to be ab - bc -de but it's ordered randomly.
What's not true?
in hashmap, insertion order is not maintained, so item inserted last may accessed first. If you want to maintain order of insertion, use linkedhashmap instead.
Update : Answer by jitendra sharma is the best :
A treemap costs a lot more than a linkedhashmap and adds nothing to your project if you only need to keep original insertion order.
Hashmap cannot get sorted. That's part of their efficiency.
If you need sorting, then use a TreeMap.
Good luck.
You should either call adapter.notifyDataSetChanged() or spinTest.setAdapter(adapter) after you sorted your list.
spinTest.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
urlDebug.setText(list.get(arg2).toString());
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spinTest.setAdapter(adapter);
// TODO: Sort the list
// Some code here
adapter.notifyDataSetChanged();

Categories

Resources