Put HashMap<String,String> into ListVIew with section headers - java

I have a HashMap of this data:
{Chefs Choice=Vegetable Samosa with Yogurt Sauce},
{Chefs Choice=Tomato Red Pepper Chutney},
{Cold Cereal=Miscellaneous/Peripherals}, {Dessert=Cheesecake Slice},
{Dessert=Banana Cream Pie with Caramel Topping}
And now I want to put this data into a ListView that will look like this.
So that the key,s are all section headers and then the values of each key goes in that section header. I thinking of using a base adapter but not quite sure how to get it right. Or if there is a better way for me to organize my data. I am also open to that.
Thanks for the help in advance :)
Here is how I add data:
ArrayList<HashMap<String, String>> blogPosts = new ArrayList<HashMap<String, String>>();
while (eventType != XmlResourceParser.END_DOCUMENT) {
String tagName = xmlData.getName();
HashMap<String, String> blogPost = new HashMap<String, String>();
switch (eventType) {
case XmlResourceParser.START_TAG:
if (tagName.equalsIgnoreCase("day")) {
currentDay = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("meal")) {
currentMeal = xmlData.getAttributeValue(null, "name");
}
if (tagName.equalsIgnoreCase("counter") && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
mealArray.add(xmlData.getAttributeValue(null, "name"));
counter = xmlData.getAttributeValue(null, "name");
}
break;
case XmlResourceParser.TEXT:
if (currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
if (xmlData.getText().trim().length() > 0) {
Log.i(TAG, blogPost + "");
blogPost.put(counter, xmlData.getText());
blogPosts.add(blogPost);
}
}
break;
case XmlPullParser.END_TAG:
recordsFound++;
break;
}
eventType = xmlData.next();
}

You can store the main header tag as arraylist.
Data structure will be like this:
Main tag of hashmap will be coming from arraylist and its value will be list of hashmap again...
Like tag 'chef choice': vegatable ssamosa and tomato red
// list contain your top header.....
List<String> arr=new ArrayList<String>();
//list to store complete data structure.
List<HashMap<String, List<HashMap<String, String>>>> list =new ArrayList<HashMap<String,List<HashMap<String,String>>>>();
// setting the data structure
HashMap<String, List<HashMap<String, String>>> hash=new HashMap<String, List<HashMap<String,String>>>();
List<HashMap<String, String>> hash1=new ArrayList<HashMap<String,String>>();
HashMap<String, String> hash2=new HashMap<String, String>();
hash2.put("tag", "vegetable");
hash1.add(hash2);
// getting tag from tag list......
hash.put(list.get(i).toString(), hash1);
list.add(hash);

Related

Iterate over ArrayList of ArrayList of Map

I use SimpleExpandableListAdapter to create ExpandableListView for my application. I want to know better how to work with lists and maps and what they are in practice.
//collection for elements of a single group;
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
I know how to iterate over ArrayList of Maps, it is not a problem for me, but I got stuck.
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
for (String phone : phonesHTC) {
m = new HashMap<>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
childDataItem = new ArrayList<>();
for (String phone : phonesSams) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
for (String phone : phonesLG) {
m = new HashMap<String, String>();
m.put("phoneName", phone);
childDataItem.add(m);
}
childData.add(childDataItem);
And I want to Log what childData contains (<ArrayList<Map<String, String>>), but I don't sure that I did that right. ( 2nd loop is a simple ArrayList of Map iteration)
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
Log.d("MyLogs", "(childData)value1 = " + value1);
Log.d("MyLogs", "(childData)key = " + key1);
}
}
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
}
If you want to log all the elements for childData then there is no need for the last loop, you are already fetching them in the first loop. Please remove below code from the program and it will log all items of childData.
for (Map<String, String> innerEntry : childDataItem) {
for (String key : innerEntry.keySet()) {
String value = innerEntry.get(key);
Log.d("MyLogs", "(childDataItem)key = " + key);
Log.d("MyLogs", "(childDataItem)value = " + value);
}
}
Above loop is iterating over childDataItem and you are using the same reference again and again in your code so in this case above loop will contain only most recent map items.
For simplicity, I changed your log statements to sysout and here's the example and output:
ArrayList<Map<String, String>> childDataItem;
//general collection for collections of elements
ArrayList<ArrayList<Map<String, String>>> childData;
Map<String, String> m;
childData = new ArrayList<>();
childDataItem = new ArrayList<>();
m = new HashMap<>();
m.put("phoneName", "HTC");
m.put("phoneName1", "HTC1");
childDataItem.add(m);
childData.add(childDataItem);
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "Samsung");
childDataItem.add(m);
childData.add(childDataItem);
// создаем коллекцию элементов для третьей группы
childDataItem = new ArrayList<>();
m = new HashMap<String, String>();
m.put("phoneName", "LG");
childDataItem.add(m);
childData.add(childDataItem);
for (ArrayList<Map<String, String>> outerEntry : childData) {
for(Map<String, String> i:outerEntry ) {
for (String key1 : i.keySet()) {
String value1 = i.get(key1);
System.out.println("MyLogs (childData)value1 = " + value1);
System.out.println("MyLogs (childData)key = " + key1);
}
}
}
Output
MyLogs (childData)value1 = HTC1
MyLogs (childData)key = phoneName1
MyLogs (childData)value1 = HTC
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = Samsung
MyLogs (childData)key = phoneName
MyLogs (childData)value1 = LG
MyLogs (childData)key = phoneName
So as you probably know, an array list is just a sequential store of data objects. And a map is a key-value pair mapping where the key is used as the lookup and must be unique. That is to say in a Map you may have many duplicate values but only one key.
As for iterating over a Map you can use an entry set which makes it a little easier. So if you wanted to iterate over an object of type <ArrayList<Map<String, String>> it would look something like this for your childDataItem class.
for(Map<String, String> map : childDataItem){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
And in your other case, the example is the same except you have another layer of array list.
for(List<Map<String, String>> childDataItemList : childData){
for(Map<String, String> map : childDataItemList){
//Take each map we have in the list and iterate over the keys + values
for(Map.Entry<String, String> entry : map){
String key = entry.getKey(), value = entry.getValue();
}
}
}

How to add distinct values form one list of hash map to another list of hash map

Could someone help me out in getting the correct list with no duplicates.
I have a list of hash map say "HashMap map" whose size is 4.
The key value pair is something similar to the below
("uri_path","/shophome/index")
("AvgResp","30.00")
("count", "3");
("status","200");
I want to create another List of Hashmap which contains single entry for "uri_path" and the average and count calculated accordingly. This is what i am trying out.Ideally the size of the new list should be lesser than the original .Can someone help understand were it is going wrong
HashMap<String, String> processedMap = null;
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> map : artEvents) {// list that contains the values
processedMap = new HashMap<String, String>();
String uri_path= map.get("uri_path");
Double art = Double.parseDouble(map.get("avgRespT"));
count =Integer.parseInt(map.get("count"));
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
processedMap.put("uri_path",uri_path);
processedMap.put("avgRespT",String.valueOf(art));
processedMap.put("count", String.valueOf(count));
artProcessedEvents.add(processedMap);
}
}
Try this code:
List<HashMap<String, String>> artEvents = ...;
//this map stores all of the result maps (one map per uri_path, uri_path is the key in this uniqueUriMap, map itself being a value).
HashMap<String, HashMap<String, String>> uniqueUriMap = new HashMap<String, HashMap<String, String>>();
for (HashMap<String, String> mapBeingProcessed : artEvents)
{
String uri_path = mapBeingProcessed.get("uri_path");
Double art = Double.parseDouble(mapBeingProcessed.get("avgRespT"));
Integer count =Integer.parseInt(mapBeingProcessed.get("count"));
if (uniqueUriMap.containsKey(uri_path))
{
Double artFromMap = Double.parseDouble(uniqueUriMap.get(uri_path).get("avgRespT"));
int countFromMap = Integer.parseInt(uniqueUriMap.get(uri_path).get("count"));
count = count + countFromMap;
art = ((art * count) + (artFromMap * countFromMap)) / count;
}
HashMap<String, String> newUriMap = new HashMap<String, String>();
newUriMap.put("uri_path",uri_path);
newUriMap.put("avgRespT",String.valueOf(art));
newUriMap.put("count", String.valueOf(count));
uniqueUriMap.put(uri_path, newUriMap);
}
//result list.
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
artProcessedEvents.addAll(uniqueUriMap.values());
The problem was with storing the temp values. This:
if (processedMap.containsValue(uri_path))
always returned false as you initialized processedMap inside the loop.
Here is the problem,
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
You have to get the value from the "map" (for loop variable) and manipulate it. And also processedMap will be empty for every run and that needs to be removed.
You seem to be confusing yourself a lot here but this would help.
In order to remove duplicates and update your parameters you would need to change processedmap from a simple string->string hashmap to a string->Hashmap i.e as shown below.Following that you would need to add it to the list via an iterator.
HashMap<String, HashMap<String, String>> processedMap = new HashMap<String, HashMap<String, String>>();
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> map : artEvents) {// list that contains the values
String uri_path= map.get("uri_path");
Double art = Double.parseDouble(map.get("avgRespT"));
count =Integer.parseInt(map.get("count"));
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
//Create a new Hashmap
HashMap<String, String> updatedMap=new HashMap<String, String>();
updatedMap.put("uri_path",uri_path);
updatedMap.put("avgRespT",String.valueOf(art));
updatedMap.put("count", String.valueOf(count));
processedMap.put(uri_path,updateMap);
}
//Iterate and add elements to the list
for (Map.Entry<String, HashMap<String, String>> entry : processedMap.entrySet())
{
artProcessedEvents.add(entry.getValue());
}
}
Thanks Michal and others your suggestions
The below code solved my issues
List<HashMap<String, String>> artEvents =new ArrayList<HashMap<String, String>>();
//this map stores all of the result maps (one map per uri_path, uri_path is the key in this uniqueUriMap, map itself being a value).
HashMap<String, HashMap<String, String>> uniqueUriMap = new HashMap<String, HashMap<String, String>>();
for (HashMap<String, String> mapBeingProcessed : artEvents)
{
String uri_path = mapBeingProcessed.get("uri_path");
Double art = Double.parseDouble(mapBeingProcessed.get("avgRespT"));
Integer count =Integer.parseInt(mapBeingProcessed.get("count"));
if (uniqueUriMap.containsKey(uri_path))
{
Double artFromMap = Double.parseDouble(uniqueUriMap.get(uri_path).get("avgRespT"));
int countFromMap =Integer.parseInt(uniqueUriMap.get(uri_path).get("count"));
count = count + countFromMap;
art = ((art * count) + (artFromMap * countFromMap)) / count;
}
HashMap<String, String> newUriMap = new HashMap<String, String>();
newUriMap.put("uri_path",uri_path);
newUriMap.put("avgRespT",String.valueOf(art));
newUriMap.put("count", String.valueOf(count));
uniqueUriMap.put(uri_path, newUriMap);
}
//result list.
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
artProcessedEvents.addAll(uniqueUriMap.values());

Unable to add a HashMap in an Arraylist without deleting the previous element

My Code:
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc,
XMLParser file) {
Map<String, String> map = new HashMap<String, String>();
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for (int i = 0; i < Doc.getElementsByTagName("item").getLength(); i++) {
Element e = (Element) Doc.getElementsByTagName("title").item(i);
Element e2 = (Element) Doc.getElementsByTagName("description")
.item(i);
// Element e3 = (Element)Doc.getElementsByTagName("link").item(i);
map.put("titre", file.getElementValue(e));
map.put("description", file.getElementValue(e2));
// map.put("lien", file.getElementValue(e3));
// adding HashList to ArrayList
menuItems.add(map);
}
return menuItems;
}
In debug, I can see each title and description in the map. When I add my map in the arrayList, all previous key-value in the arraylist are replaced by the current key-value.
So at the end I have a arrayList with 20 same title and description.
How do I add several title and description in the arrayList without erasing all others?
You should create a new map for each menuItem. In the example below, I moved the map initializer to the for loop:
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc, XMLParser file)
{
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for(int i = 0; i < Doc.getElementsByTagName("item").getLength();i++)
{
Map<String, String> map = new HashMap<String, String>();
Element e = (Element)Doc.getElementsByTagName("title").item(i);
Element e2 = (Element)Doc.getElementsByTagName("description").item(i);
//Element e3 = (Element)Doc.getElementsByTagName("link").item(i);
map.put("titre", file.getElementValue(e));
map.put("description", file.getElementValue(e2));
//map.put("lien", file.getElementValue(e3));
// adding HashList to ArrayList
menuItems.add(map);
}
return menuItems;
}
You have to create the map in the loop:
public ArrayList<Map<String, String>> XMLToArray(String Data, Document Doc, XMLParser file) {
ArrayList<Map<String, String>> menuItems = new ArrayList<Map<String, String>>();
for(int i = 0; i < Doc.getElementsByTagName("item").getLength(); i++) {
Map<String, String> map = new HashMap<String, String>();
Element e = (Element)Doc.getElementsByTagName("title").item(i);
}
}

HashMap ArrayList show same value two times in AutoCompleteTextView suggestion

My Code:
// Reading all contacts from database
List<BNICorporateBean> contacts = db.getAllInfo();
// Each row in the list stores country name, currency and email
ArrayList<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for (BNICorporateBean cn : contacts)
{
if(!memId.trim().equalsIgnoreCase(cn.getBNIMemID().trim()))
{
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("name", cn.getMemName());
hm.put("email", cn.getMemEmail() );
hm.put("mem_id", cn.getBNIMemID());
Log.d("Result", cn._MemName+"\n"+cn._MemEmail+"\n"+cn._BNIMemID);
aList.add(hm);
}
memId= cn.getBNIMemID();
//infoArry.add(cn);
}
// Keys used in Hashmap
//String[] from = { "name","email"};
// Ids of views in listview_layout
//int[] to = { R.id.mem_name,R.id.mem_email};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(LoginActivity.this, aList, R.layout.list_member, new String[] { "name","email"},
new int[]{ R.id.mem_name,R.id.mem_email});
/** Setting the adapter to the listView */
autoComplete.setAdapter(adapter);
Takes value from database and my log text show that it returns single value, but don't know why it shows same value two times in list suggestion . Note: for some values it shows once.
I have also print my list and gives perfect result no duplicate values
for(int k=0;k<aList.size();k++)
{
System.out.println(""+aList.get(k));
}
Use it.This may help you
do{
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("name", cn.getMemName());
hm.put("email", cn.getMemEmail() );
hm.put("mem_id", cn.getBNIMemID());
Log.d("Result", cn._MemName+"\n"+cn._MemEmail+" \n"+cn._BNIMemID);
aList.add(hm);
memId= cn.getBNIMemID();
}while(!memId.trim().equalsIgnoreCase(cn.getBNIMemID().trim()));

Why doen't this for loop work?

This is an android app that gets data from two different JSON URLs. Then I want to mix their data and put them in a map. To do so, I use a nested for loop. But the problem is it only show YEARS and SYSTEMDATA2 and not SYSTEMDATA1. I think my nested loop is not correct.
Does anyone know the reason?
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
}
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist,
R.layout.list_M,
new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {
R.id.systemData1, R.id.systemData2, R.id.years});
mylist.setAdapter(adapter);
}
result should be like
Year value(SYSTEMDATA2) value(SYSTEMDATA1)
Current problem
it does not show one of the values. (SYSTEMDATA1 or SYSTEMDATA2)
http://i40.tinypic.com/2wqykvr.png
NEW UPDATE
//Getting JSON Array
JSONObject myJson1 = jsons[0];
JSONObject myJson2 = jsons[1];
try {
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray array1C1 = myJson1.getJSONArray("myDATA");
JSONArray array2C1 = array1C1.getJSONArray(1);
JSONArray array1C2 = myJson2.getJSONArray("myDATA");
JSONArray array2C2 = array1C2.getJSONArray(1);
for (int i=0; i<array2C1.length(); i++)
{
JSONObject entryJsonC1 = array2C1.getJSONObject(i);
String val1 = entryJsonC1.getString(SYSTEMDATA1);
String year = entryJsonC1.getString("date");
JSONObject entryJsonC2 = array2C2.getJSONObject(i);
String val2 = entryJsonC2.getString(SYSTEMDATA2);
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2, val2);
map.put(YEAR, year);
listValues.add(map);
}
list = (ListView) findViewById(R.id.list);
String[] adaptersKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(MultiMainActivity.this, listValues, R.layout.list2, adaptersKeys, adapterViews);
list.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now the result is like: YEAR SAME-VALUE SAME-VALUE
for(int i=0; i<array2System1.length(); i++)
{
c1 = array2System1.getJSONObject(i);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
for(int x=0; x<array2System2.length(); x++)
{
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
list = (ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(Search.this, mylist, R.layout.list_M, new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR}, new int[] {R.id.systemData1, R.id.systemData2, R.id.years});
// Shoudl be list and not mylist
list.setAdapter(adapter);
You need to put all your code in the inner loop. Currently you just close the inner loop - it runs and overwrites c2 and does nothing.
Something like:
for(int i = 0; i < array2System1.length(); i++){
c1 = array2System1.getJSONObject(i);
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
}
}
The second for loop closes very early. it should be as follows.
for(int x = 0; x < array2System2.length(); x++){
c2 = array2System2.getJSONObject(x);
//Storing JSON item in a Variable
valueSystem2 = c2.getString(SYSTEMDATA2);
year = c1.getString(YEAR);
valueSystem1 = c1.getString(SYSTEMDATA1);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2, valueSystem2);
map.put(YEAR, year);
mylist.add(map);
} // This is where it should get closed
Otherwise, you are just reassigning the c2 variable and loosing the other values execpt the last value. Now, you will be able to place the valueSystem1, valueSystem2 and YEAR values in map and then added to the list. Hope this helps
List<Map<String, String>> listValues = new ArrayList<Map<String, String>>();
JSONArray jsonArray = new JSONArray(.....); // Contains all the indicators
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject entryJson = jsonArray.getJsonObject(i);
// Check integrity
if (!entryJson.hasKey("country")) throw new Exception("No 'country' key found");
if (!entryJson.hasKey("value")) throw new Exception("No 'value' key found");
if (!entryJson.hasKey("date")) throw new Exception("No 'date' key found");
// Get country
JSONObject countryJson = entryJson.getJsonObject("country");
if (!countryJson.hasKey("value")) throw new Exception("No 'value' key found");
String country = countryJson.getString("value");
// Get population
String population = entryJson.getString("value");
// Get year
String year = entryJson.getString("date");
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, country);
map.put(SYSTEMDATA2, population);
map.put(YEAR, year);
// Add to list
listValues.add(map);
}
// Get the ListView
ListView Llist = (ListView) findViewById(R.id.list);
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2, YEAR};
int[] adapterViews = new int[] {R.id.systemData1, R.id.systemData2, R.id.years};
ListAdapter adapter = new SimpleAdapter(Search.this, listValues, R.layout.list_M, adapterKeys, adapterViews);
// Attach the adapter to the listView
Llist.setAdapter(adapter);
Here is another way that should work better. I haven't tested the code as it was made in notepad. Please tell me if you have any issue.
Because you have defined this:
private static final String SYSTEMDATA1 = "value";
private static final String SYSTEMDATA2 = "value";
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
The issue appears where you are creating your map:
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, valueSystem1);
map.put(SYSTEMDATA2_KEY, valueSystem2);
map.put(YEAR, year);
A Map is:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value
From the docs for put() method:
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
So you place valueSystem1 using SYSTEMDATA1 as key, which is "value" and then you place valueSystem2 using SYSTEMDATA2 as key, which is ALSO "value", so you are overwriting valueSystem1!
See the edit below...
EDIT:
I'm guessing that to retrieve your values, you must use keys which are "value", that's fine, but to insert in the map later, you must have unique keys. If you still have SYSTEMDATA1="value" and SYSTEMDATA2="value", add one more which you'll use to store in the map and later in the adapter:
//you can't have 2 entries with the same key
private static final String SYSTEMDATA2_KEY = "value2";
// Create a new Map
Map<String, String> map = new HashMap<String, String>();
map.put(SYSTEMDATA1, val1);
map.put(SYSTEMDATA2_KEY, val2);
map.put(YEAR, year);
and then, when you set your adapter keys:
// Create a new adapter to attach this listView
String[] adapterKeys = new String[] {SYSTEMDATA1, SYSTEMDATA2_KEY, YEAR};
Code updated in my original answer.

Categories

Resources