java.util.hashmap cannot be cast to java.util.list - java

i'm trying to retrieve data from a hashmap with multiple values for 1 key and set it to a listview but im gettting the error java.util.hashmap cannot be cast to java.util.list.
The code is as follows:
ListView lv = (ListView)findViewById(R.id.list);
//hashmap of type `HashMap<String, List<String>>`
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
for (int i = 0; i < j; i++) {
values.add(value1);
values.add(value2);
hm.put(key, values);
}
and to retrieve the values and put in a listview
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, (List<? extends Map<String, ?>>) hm,
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
how can i fix this?

Wrap the Map in a List to match the expected type List<? extends Map<String, ?> of the constructor SimpleAdapter:
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, Arrays.asList(hm),
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });
Refer to this example

You must change the order how you add data. According to the documentation of SimpleAdapter, you must create a list of maps, where each entry of the list represents one row of data. The maps must contain the column names as key, and the column value as value.
So to create 3 rows with 3 columns you would do:
List<? extends Map<String, ?>> data = new ArrayList<? extends Map<String, ?>>();
for (int i=0; i < 3; i++) {
Map<String, String> row = new HashMap<String, String>();
row.put(key, "key in row " + i);
row.put(value1, "value1 in row " + i);
row.put(value2, "value2 in row " + i);
data.add(row);
}
Then create your SimpleAdapter instance:
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, data,
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });

Related

Combine String Array and Iterator and sort

I have 2 sets of values in my app - 1 from resources file and 1 from sharedpreferences. Is there an easy way to combine these both and create a Sorted List for the adapter? Here is my code:
Spinner copyFromCity = (Spinner) findViewById(R.id.spinner);
Resources res = getResources();
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
// Necessary to add Iterator String to an adapter
ArrayList<String> sortedPredefinedCities = new ArrayList<String>();
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
new ArrayList(Arrays.asList(predefinedCities)));
// Add values from our custom cities onto the Adapter via SharedPreferences
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
while(userCities.hasNext()){
adapter.add(userCities.next());
}
/* TODO Way to sort both these values into alphabetical order */
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
copyFromCity.setAdapter(adapter);
Adding readCitiesFromPref() method for clarifying why Iterator is being returned
protected Iterator<String> readCitiesFromPref() {
// See if preferences store this
JSONObject citiesList = null;
Iterator<String> userCities = null;
try {
// Yes, so get the values out
citiesList = new JSONObject(prefs.getAll());
userCities = citiesList.keys();
} catch (NullPointerException e1) {
//TODO
}
return userCities;
}
What I think is add those arrays/list to a List, sort and set it to adapter
String [] predefinedCities = res.getStringArray(R.array.predefined_cities);
prefs = getSharedPreferences(MY_PREFS_NAME, Context.MODE_PRIVATE);
Iterator<String> userCities = readCitiesFromPref(); // unsorted values
List<String> copyOfCities = new ArrayList<String>();
while (userCities.hasNext()){
copyOfCities.add(userCities.next());
}
ArrayList<String> sortedCities = new ArrayList<String>();
sortedCities.addAll(copyOfCities);
sortedCities.addAll(Arrays.asList(predefinedCities));
Collections.sort(sortedCities);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
sortedCities);
You can do like this:
Convert the string array to a List
convert the Iterator to List
Combine them
Sortthem like Collections.sort(yourCombinedList);
feed them to the adapter

Custom View Layout - " List<Map> cannot be converted to List<? extends Map<String,?>> "

I have a custom list view which allows clicking on items in the list.
The code that worked well, similar to many examples on google's own site, and compiled successfully until more recent java, is this:
List<Map> myMapList = new ArrayList<Map>();
Map<String, String> myMap = new HashMap<String, String>();
private ListView myListView;
for (int i = 0; i < mydata.length(); i++) {
JSONObject t = mydata.getJSONObject(i);
myMap = new HashMap<String, String>();
myMap.put("field_1", t.getString("field_1"));
.... (more of these)
myMapList.add(myMap);
}
String[] layoutNames = new String[] { "field_1", "field_2", "field_3",
"field_4", "field_5" };
int[] layoutIDs = new int[] { R.id.field_1, R.id.field_2, R.id.field_3,
R.id.field_4, R.id.field_5};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
(List<? extends Map<String, ?>>) myMapList, R.layout.my_list_row,
layoutNames, layoutIDs );
myListView.setAdapter(adapter);
At first, warnings were given, but now it is a compile-time error.
error: incompatible types: List<Map> cannot be converted to List<? extends Map<String,?>>
So how to I feed my String / Integer combo into List<> with the new rules?
Solution Note:
Answer Goes to Aeshang, see below. Note that this solution also gets rid of the need for the "(List>)" cast, so that line now reads:
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
myMapList, R.layout.my_list_row, layoutNames, layoutIDs );
Easier on the eyes, too.
You have to change this line
List<Map> myMapList = new ArrayList<Map>();
to
List<Map<String, String>> myMapList = new ArrayList<Map<String, String>>();

Put Hashmap into Arraylist<HashMap>

I'm new at android. I trying to get the data from Database and put it into HashMap. But I got a little problem here. I got an error when I try to put the data that I get.
I put a comment on the error line in my code. You can check it below
Here's my class
private static final String TAG_ITEM_NAME = "item_name";
// Hashmap for ListView
ArrayList<HashMap<String, String>> searchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchlist = new ArrayList<HashMap<String, String>>();
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult(searchResult);
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
//AllItem item_name = all_Items.put(cn.getItem_name(), cn);
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
}
searchlist.add(all_Items);
ListAdapter adapter = new SimpleAdapter(
Search.this, searchlist,
R.layout.searchlayout, new String[] {TAG_ITEM_NAME},
new int[] { R.id.category_name}
);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
The error said The Method put(String, Allitem) int type Hashmap<String,Allitem> is not applicable for the argument (String, String)
How to fix this error? Thanks before :D
all_items takes a String and an AllItem, but you are placing two Strings into it in this line:
// TAG_ITEM_NAME is a String and item_name is also a String
all_Items.put(TAG_ITEM_NAME,item_name);
You try to put in the map as a value string but you map expect as a value AllItem, so you must modify your code in this way:
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
all_Items.put(item_name , cn );
}
This code will add your class object to the map with the key which equals to your object name.
all_Items is defined as a hashmap to contain <String, AllItem> key value pairs as defined here:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
but you are trying to push <String,String> key value pair into your all_Items hashmap :
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
It seems you want to push the AllItem object against its item_name, which can be done as:
all_Items.put(item_name, cn);
Your HashMap is as follows:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
This means it has String keys and AllItem values. You can put a AllItem object inside this HashMap.
When you write
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
you are putting a String inside the HashMap hence it is giving error.
You should be doing:
all_Items.put(TAG_ITEM_NAME,cn);
Your hashmap is <String, Allitem>. While you try to put <String, String> in it.
all_Items.put(TAG_ITEM_NAME, item_name);
should be changed to
all_Items.put(TAG_ITEM_NAME, cn);
Hope you got the difference.
I dont see connection in the code but using the given information, your error probably is related to your searchlist variable in your code.
change this:
ArrayList<HashMap<String, String>> searchlist;
to this:
ArrayList<HashMap<String, AllItem>> searchlist;
it's because you declared HashMap<String, AllItem> and you try to putall_Items.put(TAG_ITEM_NAME,item_name); which would probably be HashMap<String, String>().

Android: Getting arrayList elements by index

I have my two arraylist and I have merged their data like this
ArrayList prayerNames={Fajar,Zohar,Asar,Magrib,Isha};
ArrayList prayerTime={4:04am,2:58pm,4:20pm,5:09pm,8:10pm}
ArrayList<String> mergedList= new ArrayList<String>();
for(int i=0;i<prayersTime.size();i++){
mergedList.add(prayerNames.get(i)+""+prayerTimes.get(i));
}
fajarText.append(mergedList.get(0));
zoharText.append(mergedList.get(2));
asarText.append(mergedList.get(4))
But now when I want to get data from merged list with specific index my activity got stops.
Need Help
Your ArrayList initialization is not correct. Try this:
ArrayList<String> prayerNames = new ArrayList<String>();
prayerNames.add("Fajar");
prayerNames.add("Zohar");
prayerNames.add("Asar");
prayerNames.add("Magrib");
prayerNames.add("Isha");
ArrayList<String> prayerTimes = new ArrayList<String>();
prayerTimes.add("4:04am");
prayerTimes.add("2:58pm");
prayerTimes.add("4:20pm");
prayerTimes.add("5:09pm");
prayerTimes.add("8:10pm");
ArrayList<String> mergedList = new ArrayList<String>();
for (int i = 0; i < prayerTimes.size(); i++) {
mergedList.add(prayerNames.get(i) + "" + prayerTimes.get(i));
}
fajarText.append(mergedList.get(0));
zoharText.append(mergedList.get(2));
asarText.append(mergedList.get(4));

HashMap values not being appended to ListView

i'm trying to retrieve data from a hashmap with multiple values for 1 key and set it to a listview,but instead of setting the values
into the listview and displaying the listview,all that is displayed is the array(without the key).
The code is as follows:
ListView lv = (ListView)findViewById(R.id.list);
//hashmap of type `HashMap<String, List<String>>`
HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
for (int i = 0; i < j; i++) {
values.add(value1);
values.add(value2);
hm.put(key, values);
}
and to retrieve the values and put in a listview
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, Arrays.asList(hm),
R.layout.list_item, new String[] { key,
value1,value2},
new int[] { R.id.id, R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
an example is where the key=1,value2=2 and value3=3,it will display the an array that looks like [2,3].
how do i get it to display the lisview and add the key too?
SimpleAdapters Consturctor states as it's second parameter:
data: A List of Maps. Each entry in the List corresponds to one row in
the list. The Maps contain the data for each row, and should include
all the entries specified in "from"
but HashMap<String, List<String>> hm is a map of lists. So like List<Map<String,String>> hm would be the datatype you probably need.
Here is the edited source:
ListView lv = (ListView)findViewById(R.id.list);
List<Map<String,String>> mapList = new ArrayList<Map<String, String>>();
Map<String,String> mapPerRow;
for (int i = 0; i < rowNumbers; i++) {
mapPerRow = new HashMap<String, String>();
mapPerRow.put("column1", value1);
mapPerRow.put("column2", value2);
mapList.add(mapPerRow);
}
ListAdapter adapter = new SimpleAdapter(
MainActivitty.this, mapList,
R.layout.list_item, new String[] { "column1", "colum2"},
new int[] { R.id.value1,R.id.value2 });
// updating listview
lv.setAdapter(adapter);
I don't get why you want the key in it (just add Strings to the map if you need more)?

Categories