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)?
Related
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
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>>();
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>().
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 });
I read a tutorial, and it uses SQLlite and "SimpleCursorAdapter" to fill the list with items.
This is the code the tutorial taught me.
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
However...what if I want to fill it with XML data? Is it the same method? Can someone give me an example (in code)? thanks.
The example is using a CursorAdapter because a Cursor object is returned by the NotesDbAdapter (if i remember correctly ) fetchAllNotes method. I don't know if there is a way to pass in raw XML to create a list but you can use name/value pairs in a HashMap to create a list using the SimplelistAdapter.
You can parse your xml and or json and build a hash table with it and use that to populate a list. The following example doesn't use xml, in fact it's not dynamic at all, but it does demonstrate how to assemble a list at runtime. It's taken from the onCreate method of an activity that extends ListActivity. The all uppercase values are static constant strings defined at the top of the class, and are used as the keys.
// -- container for all of our list items
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
// -- list item hash re-used
Map<String, String> group;
// -- create record
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString( R.string.option_create ) );
group.put( KEY_HELP, getString( R.string.option_create_help ) );
group.put( KEY_ACTION, ACTION_CREATE_RECORD );
groupData.add(group);
// -- geo locate
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString(R.string.option_geo_locate ) );
group.put( KEY_HELP, getString(R.string.option_geo_locate_help ) )
group.put( KEY_ACTION, ACTION_GEO_LOCATE );
groupData.add( group );
// -- take photo
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString( R.string.option_take_photo ) );
group.put( KEY_HELP, getString(R.string.option_take_photo_help ) );
group.put( KEY_ACTION, ACTION_TAKE_PHOTO );
groupData.add( group );
// -- create an adapter, takes care of binding hash objects in our list to actual row views
SimpleAdapter adapter = new SimpleAdapter( this, groupData, android.R.layout.simple_list_item_2,
new String[] { KEY_LABEL, KEY_HELP },
new int[]{ android.R.id.text1, android.R.id.text2 } );
setListAdapter( adapter );