I had seen many examples regarding Hashmap Data but I am not getting the data as required.
Here is my code:
HashMap<String,ArrayList<String>> citylist = new HashMap<String, ArrayList<String>>();
ArrayList<String> Gujarat = new ArrayList<String>();
Gujarat.add("Surat");
Gujarat.add("Baroda");
Gujarat.add("Ahmedabad");
ArrayList<String> Rajasthan = new ArrayList<String>();
Rajasthan.add("Udaipur");
Rajasthan.add("Jaipur");
ArrayList<String> UP= new ArrayList<String>();
UP.add("Lucknow");
UP.add("Agra");
citylist.put("Gujarat", Gujarat);
citylist.put("UP", UP);
citylist.put("Rajasthan", Rajasthan);
It is in recyclerview how to get this type of data in BindViewHolder?
Toast is coming like:
{Rajasthan=[Udaipur, Jaipur], UP=[Lucknow, Agra], Gujarat=[Surat, Baroda, Ahmedabad]}
I had used this method to get but error is coming:
public void onBindViewHolder(MyViewHolder holder, int position) {
ArrayList<String> lst = citylist.get("" + position);
for (Integer i = 0; i < lst.size(); i++) {
holder.tv.setText(citylist.toString());
Log.e("Hashmap....", ""+holder.tv );
}
the output should be like Gujarat is state and surat baroda and ahmedabad are cities?
First create one ArrayList with all state :
ArrayList<String> stateList = new ArrayList<String>();
stateList.add("Gujarat");
stateList.add("UP");
stateList.add("Rajasthan");
Second create one HashMap with each state name as Key and each state city as Value:
HashMap<String,ArrayList<String>> stateCityMap = new HashMap<String,ArrayList<String>>()
ArrayList<String> gujaratCityList = new ArrayList<String>();
gujaratCityList.add("Ahmedabad");
gujaratCityList.add("Surat");
gujaratCityList.add("Baroda");
.......................
ArrayList<String> upCityList = new ArrayList<String>();
upCityList.add("Lucknow");
upCityList.add("Agra");
..........................
ArrayList<String> rajasthanCityList = new ArrayList<String>();
rajasthanCityList.add("Udaipur");
rajasthanCityList.add("Jaipur");
...........................
stateCityMap.put("Gujarat",gujaratCityList);
stateCityMap.put("UP",upCityList);
stateCityMap.put("Rajasthan",rajasthanCityList);
Now get all city name based on state in Adapter :
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.e("State : ",stateList.get(position));
ArrayList<String> cityList= (ArrayList<String>)stateCityMap.get(stateList.get(position));
for(String cityName : cityList){
Log.e("City : ",cityName);
}
}
you can get like below.
Iterator iterator = map.keySet().iterator();
while(iterator.hasNext()) {
String key=(String)iterator.next();
String value=(String)map.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
HashMaps do not preserve ordering:
This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant
over time.
Take a look at LinkedHashMap, which guarantees a predictable iteration order.
You might wanna try something like this.
for (Map.Entry<String, ArrayList<String>> entry : citylist.entrySet())
{
String key = entry.getKey(); // Your State
String value = entry.getValue(); // Your List of Cities.
// Split data and insert in Views
}
However I recommend (for easy to use case) keep a List of all the states and get Value from HashMap using keys from this List of states.
Please check it :
ArrayList<HashMap<String, String>> arrayList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> h1 = new HashMap<String, String>();
h1.put("h1_key_1", "h1_value_1");
h1.put("h1_key_2", "h1_value_2");
arrayList.add(h1);
for (HashMap<String, String> hashMap : arrayList) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
Try This:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Related
I have 2 item types in my listview, Venue and Distance.
List<String> ls_Distance;
List<String> ls_Venue;
ls_Distance = new ArrayList<String>();
ls_Venue = new ArrayList<String>();
I'm adding string items into both list arrays in a for loop.
(I'm assuming sort function can sort a list of numbers that are in string format e.g. "9","15","20" etc.. and I don't need to covert to int first?)
ls_Distance.add(data_Distance);
ls_Venue.add(data_Venue);
I would like to sort the items by distance (showing lowest distance first), and maintain the index of the venue.
Note: This sorting can only be done once data is added to array and not before (distance obtained from location updates calculations)
Then I want to set my listview adpater after sorting:
ListViewRowCount = ls_Venue.size();
lv.setAdapter(lv_custom_adapter);
EDIT:
My code for sorting (not working)
private void sortByDistance() {
Collections.sort(ls_Distance, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
Log.v("TAG", "zzz_compare_lhs: " +lhs);
Log.v("TAG", "zzz_compare_rhs: " +rhs);
return lhs.compareTo(rhs);
}
});
//setAdapter();
}
Resolved: (Using TreeMap)
private void consolidateData() {
if (currentLat != 0.0){
Map<Integer, String> map = new TreeMap<Integer, String>();
for (int i=0;i<stringArr_markerVenue.size();i++){
data_Distance = Integer.parseInt(stringArr_markerDistance.get(i));
data_Venue = stringArr_markerVenue.get(i);
//ls_Distance.add(data_Distance);
//ls_Venue.add(data_Venue);
map.put(data_Distance, data_Venue);
}
TreeMap<Integer, String> sorted = new TreeMap<>(map);
Set<Map.Entry<Integer, String>> mappings = sorted.entrySet();
System.out.println("HashMap after sorting by keys in ascending order ");
for(Map.Entry<Integer, String> mapping : mappings){
System.out.println(mapping.getKey() + " ==> " + mapping.getValue());
int data_Distance = mapping.getKey();
String data_Venue = mapping.getValue();
Log.v("TAG", "zzz_com: " + data_Distance + " ==> " + data_Venue);
ls_Distance.add(data_Distance+"");
ls_Venue.add(data_Venue);
}
setAdapter();
}
}
private void setAdapter() {
ListViewRowCount = ls_Distance.size();
lv.setAdapter(lv_custom_adapter);
}
I parse json data and display it in listview with CHOICE_MODE_MULTIPLE. I trying to get the key of a Hashmap in my case but I only manage to get the value.
Json data
57->Steak Doness
58->Size
59->Cooking Method
63->Coldness
Here is the coding
String option_data = jsonObject.getString("option_data");
JSONObject jsonObject1 = new JSONObject(option_data);
Iterator<String> iterator = jsonObject1.keys();
ArrayList arrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = null;
while (iterator.hasNext()) {
String id = iterator.next();
String name = jsonObject1.getString(id);
map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
arrayList.add(name);
}
ArrayAdapter adapter = new ArrayAdapter<String>(item_add.this, android.R.layout.simple_list_item_multiple_choice, arrayList);
final ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String selected = "";
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for (int i = 0; i < listView.getCount(); i++) {
if (sparseBooleanArray.get(i)) {
selected += listView.getItemAtPosition(i).toString() + ",";
}
}
Log.d("selected", selected);
}
});
With the logcat, it shows
D/selected: Steak Doness,Size,
However, what I want to get is the Key in Hashmap which means "id" when click the button . Anyone knows how to do it?
Use the following way to iterate and find values of keys
HashMap <String,String> mapOne= new HashMap();
mapOne.put("1","1value");
mapOne.put("2","2value");
mapOne.put("3","3value");
for(Map.Entry<String, String> mapEntry : mapOne.entrySet()){
if (mapEntry.getValue().equals("3value")) {
//System.out.println(mapEntry.getKey());
Log.d("selected", mapEntry.getKey());
}
}
I want to store a String array in the database, but I got values from another activity as an ArrayList<Hashmap<String, String>>. How should I convert this ArrayList into a String array?
Code:
HashMap <String, String> h1 = new HashMap <String, String> ();
h1.put("member_id", member_id);
h1.put("categoryname", category_name);
h1.put("routinetype", routine_type);
h1.put("targettype", target_type);
h1.put("days", countOfDays);
h1.put("point", points);
h1.put("daystring", listOfDayString);
h1.put("create_date", strDate);
arrayList1.add(h1);
Simply use:
String[] strArray = new String[urArrayList.size()];
strArray = urArrayList.toArray(strArray);
EDIT:
Then you can simply use this:
int i = 0;
String strArr[] = new String[urArrayList.size()];
for (HashMap<String, String> hashMap : urArrayList) {
for (String value : hashMap.values()) {
strArr[i] = value ;
i++;
}
}
I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).
I am trying to store data in Android. I am using the SharedPreferences. And I am retrieving these data by using:
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
Map<String, ?> keys = myPrefs.getAll();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.i("map values", entry.getKey());
//some code
}
EDIT:
But data retrieved are not in the same order as they were inserted. How to get the same order?
Copy the resulting Map into an implementation of SortedMap, e.g. TreeMap.
Like this (sort by key):
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
TreeMap<String, ?> keys = new TreeMap<String, Object>(myPrefs.getAll());
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Log.i("map values", entry.getKey());
//some code
}
To sort by value & not lose any key-value pairs (since a Map will readily allow duplicate values mapping to different keys) you'd need to first convert it into
a List and sort that.
List<Pair<Object, String>> sortedByValue = new LinkedList<Pair<Object,String>>();
for (Map.Entry<String, ?> entry : keys.entrySet()) {
Pair<Object, String> e = new Pair<Object, String>(entry.getValue(), entry.getKey());
sortedByValue.add(e);
}
// Pair doesn't have a comparator, so you're going to need to write one.
Collections.sort(sortedByValue, new Comparator<Pair<Object, String>>() {
public int compare(Pair<Object, String> lhs, Pair<Object, String> rhs) {
// This is a naive and shitty comparator, but it works for
// arbitrary objects. Sort of. Tweak depending on the order you need.
String sls = String.valueOf(lhs.first);
String srs = String.valueOf(rhs.first);
int res = sls.compareTo(srs);
// Sort on value first, key second
return res == 0 ? lhs.second.compareTo(rhs.second) : res;
}
});
for (Pair<Object, String> pair : sortedByValue) {
Log.i("map values", pair.first + "/" + pair.second);
}
Add a property with the order, like so...
First save the settings...
public static void saveSettings(final Editor editor, final String [] order) {
final String csl = toString(order);//comma separated
editor.putString("insert_order", csl);
for (int i = 0; i < values.length; i++) {
editor.putString(values[i], your_value[i]);
}
}
Now load them:
public static List<String> loadSetting(final SharedPreferences preferences) {
final List<String> inOrder = new ArrayList<>();
final String[] ordering = preferences.getString("insert_order", "").split(",");
for (final String item : ordering) {
final String value = (String) preferences.getString(item, "");
inOrder.add(value);
}
return inOrder;
}