HashMap Iteration only shows last element - android

I'm trying to implement an expandable listview with data coming from a database. I've already tried having the data added within the codes and it works so I'm now trying to have dynamic data from the database populate the listview.
The data is grouped in two, the main category and the member. For example if the main category is fruit, it's members may include mango, avocado, apples, etc. If animals, it may have horses, eagle, shark. The data always comes in pairs such as Animal, Horses; Animal, Eagle; Fruit, Apples. The expandable listview should appear as:
Animal
-- Horses
-- Eagle
Fruit
-- Apples
My code below can already determine the main group so the headers already display the main groupings of Fruit and Animal. By using
group_member.put(family_name, member_name);
I linked the member to the main category. My problem now is how to code for the iteration to group the members to the main category. So far I've already tried using iterator based on the sample codes given here in stackoverflow and from other sites however only the last elements of each group is display. I've also tried using the for-each loop bur still no success.
String json = jsonParser.makeHttpRequest(URL_COMPONENTS, "POST", params);
JSONArray components = null;
ArrayList<HashMap<String, String>> componentList;
List<String> main_group = new ArrayList<String>();
HashMap<String, String> group_member = new HashMap<String, String>();
try {
components = new JSONArray(json);
if (components != null) {
for (int i = 0; i < components.length(); i++) {
JSONObject c = components.getJSONObject(i);
String family_name = c.getString(TAG_FAMILY_NAME);
String member_name = c.getString(TAG_MEMBER_NAME);
main_group.add(family_name);
group_member.put(family_name, member_name);
if (!listDataHeader.contains(main_group))
listDataHeader.add(main_group);
componentList.add(group_member);
}
}
}
Please help. Thanks in advance!

If you're using HashMap you can't have a key more than once in your list. Each key must be unique.
This could be a solution:
HashMap<String, ArrayList<String>> group_member = new HashMap<String, ArrayList<String>>();
... using the Hashmap as a directory and the key is returning an Arraylist of the family members.

Related

RecyclerView which display and return different Values

I am displaying list of check-boxes in horizontal RecyclerView.
It display values such as {"Rd" , "Gr" , "Yl"} but when user selects any of this value it should return {"RED" , "GREEN" , "YELLOW")
How can I bind these two value that show and return differently?
I am taking display values from R.string-arry
I created another string-array of actual values, and when user checked any of checkboxes I get that ID and replaced it with actual values.
For e.g. If user has selected "Gr" I get ID=1 then replaced with actual string-array
But this only works when code-color and original-color are in order. In my app I sometimes use Red,green,blue or sometimes green,yellow,blue. So, this won't help me.
From what I understood, you need a mapping between GR and Green, RD and Red etc.
You can try using a Hashmap.
HashMap<String,String> colourMap = new HashMap<>();
colourMap.put("GR","GREEN");
colourMap.put("RD","RED");
And then you can retrieve the respective value for your colour code:
String colour = colourMap.get("GR");
You can use a HashMap which will bind the two arrays as key value pair
public HashMap<String,String> bindColors() {
HashMap<String,String> map = new HashMap<>();
int length = orginalColors.length;
for (int i = 0; i < length; i++) {
map.put(orginalColors[i], codeColors[i]);
}
return map;
}
And for getting the Colors in code.
HashMap<String, String> keyPair = bindColors();
orginalColorsNewArray = keyPair.keySet().toArray(new String[keyPair.keySet().size()]);
codeColorsNewArray = keyPair.values().toArray(new String[keyPair.values().size()]);
or use .get() function
keyPair.get("YELLOW")
Now it will be easier for you to access the codes by id/position
Hope this helps.

Split TreeMap<List<>,List<>> into two ArrayList

i have two ArrayLists:
List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);
which i want to sort alphabetically.
For this i created a TreeMap:
Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);
First two Question
Is the map now sorted in lexicographical order? Or do i Need to do something additional?
After i have sorted them, if they are yet, i want to split them back again to List<String> and List<Drawable>. And i tried like this:
List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());
Of course it doesn't work because myMapToSort.keySet() Returns a Set and not List.
And List doesn't have an Constructor for a Set.
So how can i accomplish that and what i'm misunderstanding?
Any help is appreciated. Thanks in advance!
I figured it out by my own.
The key was to create a TreeMap with not two list but two single Objects:
Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
Then add the Items from the Arraylists one by one to the Map:
for(int i = 0; i<names.size(); i++) {
myTreeMap.put(names.get(i), drawables.get(i));
}
Now the Map is automatically sorted Lexicographical in relation with the Drawables.
That means Names and Drawables are sorted in lexicographical order.
If you want to retrieve the keys and the values and put them back in seperate ArrayLists simply type:
List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
That's it. ;)
You can use SortedSet (or SortedList) to have sorted elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.
For splitting a Map in two lists :
List<String> sortedNames = new ArrayList<String>();
List<Drawable> drawables = new ArrayList<Drawable>();
for (Map.Entry<String, Drawable> entry : map.entrySet())
{
sortedNames.add(entry.getKey()
drawables.add(entry.getValue());
}

I want to display source class array list into destination class

I want to pass Array list from one activity to another activity. I am trying like this:
I am passing array list source activity to destination activity. But the problem is I am getting only the last item at destination activity.
My code is
source.class
HashMap<String,String> hm = new HashMap<String, String>();
ArrayList<HashMap<String,String>> arl = new ArrayList<HashMap<String,String>>();
hm.put(KEY_NAME,u);//am adding these values through loop
arl.add(hm);//adding Hash Map to Array List
Intent intent = new Intent(MainActivity.this, SinglePlaceActivity.class);
intent.putExtra("arraylist", arl
startActivityForResult(intent, 500);
System.out.println("uuuuu"+arl);//upto now working good and display perfectly all array list
destination.class
ArrayList<HashMap<String, String>> arl = ArrayList<Hash
Map<String,String>>)getIntent().getSerializableExtra("arraylist");
System.out.println(arl);//am getting what i add last item in the Arrylist at source class
Iterator itr = arl.iterator();
while(itr.hasNext())
{
System.out.println(itr.hasNext);//am getting single last item multiple times.what i add last item in the Arrylist at source class
I want to display source class array list into destination class.
Try using:
Bundle.putSerializable() and Bundle.getSerializable().
Also, in:
System.out.println(itr.hasNext);
shouldn't it be its.next()?
Take also into account that using Seralizable object in Android IPC adds a significant overheard with respect to using Parcelable objects.

How to sort the arraylist from hashmap?

Im using hashmap and arraylist...
How to sort the arraylist ? eg) In hashmap values are in order like one,two,three,four,five
but i stored these values in arraylist the order changed like three,one,five,two,four
In my code groupList,gnamelist and newList are all arraylist...
In print sts PLACES are in correct order but while print on NEWLIST PLACES the order changed
How to sort this in order?
My code
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PLACE, gname);
map.put(TAG_HOTEL,lname);
// adding HashList to ArrayList
groupList.add(map);
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(gnamelist));
Collections.sort(newList,Collections.reverseOrder());
System.out.println("NEWLIST PLACES" + newList);
HashSet will store elements in an unordered fashion, and is likely the culprit of your element reordering.
List<String> newList = new ArrayList<String>(new HashSet<String>(gnamelist));
Also consider using LinkedHashMap/LinkedHashSet, which preserves the ordering of elements added to it.
Alternatively try the following:
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>();
newList.addAll(gnamelist);
Try
Collections.sort(newList);
Edit:
If you want to sort in reverse use this
Collections.sort(newList,Collections.reverseOrder());
Important:
if you want to preserve insertion order, you need to use TreeSet instead of HashSet as HashSet doesn't preserve insertion order

Android - Reading common data between Activities using a Spinner

I have an Android application which retrieves from a external server, a name and a corresponding ID (this could be 1 name and ID combo or multiple name ID combinations), these are all stored in a HashMap<String, String> - The ID as the key and the Name as the value.
What I then would like to implement is a dynamic Spinner that populates itself with the 'Names' from this HashMap and when the user selects one of these names a setting somewhere I set to the ID number. This ID number will then be used in later server requests.
My question is what is the best way to implement this custom Spinner from the HashMap so that when the option is selected the ID number is set somewhere. This ID number has to be accessible from several activities - the spinner is present in several different activities... but should have the same effect on each screen.
Design patterns and pseudo code would be hugely appreciated. At the moment the Spinner is on 2 different screens, at the top below the ActionBar, but obviously the code is in both XML layout files.
Cheers.
EDIT
Code to set names and IDs in HashMap:
// Returns a Map of blog name to blog ID associated with the authenticated user
public Map<String, String> extractBlogInfo(XMLDataExtracter blogData)
{
Log.d(TAG, "BlogOperations::extractBlogInfo()");
ArrayList<String> blogIDs = new ArrayList<String>();
ArrayList<String> blogNames = new ArrayList<String>();
Map<String, String> blogIDNamePairs = new HashMap<String, String>();
// Get ID and Names and store them in blogIDs and blogNames variables
if (blogIDs.size() == blogNames.size())
{
for(int i = 0; i < blogIDs.size(); i++)
{
blogIDNamePairs.put(blogIDs.get(i), blogNames.get(i));
}
}
else
{
// An error occured
Log.d(TAG,
"BlogOperations::extractBlogInfo() > An error occured - ID and Name array sizes do not match");
return null;
}
return blogIDNamePairs;
}
For this you can use Shared preference.. You get the Id of the selected value from spinner and stored it in shared preference..
So that you can access this value any where inside your Apps..
If you want to display the selected spinner value from Say Activity1 in Activity2 get the value from Shared preference, now it will be Id so get the corresponding Name from the Id in hash Map..
For shared preference take a look at this... and this....

Categories

Resources