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++;
}
}
Related
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
}
}
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'm building a a Gallery app using GridView and ViewPager. I'm getting the image URLs from JSON. I've got the GridView displaying the images correctly, and now I'm moving on to the ViewPager. What I think I need to do is generate a String array of the image URLs for the ViewPager Adapter. In the GridView Activity, I've created a HashMap with the id, URL, and image description strings stored. My question now is: Is it possible to generate a String Array by retrieving all the stored URL strings from the HashMap? What I need is this from the HashMap:
public static final String[] imagesStr = new String[] {
"http://www.mysite/images/building0001.jpg",
"http://www.mysite/images/building00011.jpg",
"http://www.mysite/images/building0010.jpg" };
Here's how I'm generating the HashMap:
#Override
protected Void doInBackground(Void... params) {
// Retrieve JSON Objects from the given URL address
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try {
// Locate the array name in JSON
JSArrGallery = jsonobject.getJSONArray("gallery");
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
I'm a bit unclear on how a HashMap works, but I assume that the code is going through the JSON Array and pulling each URL string out and storing it in the HashMap, right? So now can I pull all the gathered URL Strings and create a String Array with them? How would I do that?
Seems straightforward enough. After you have populated your List<HashMap<String,String>>, iterate over each map and pull the value you need from it to add to a String[]. Please refer to the following snippet:
galleryArrList = new ArrayList<HashMap<String, String>>();
jsonobject = JIJSONfunctions.getJSONfromURL(urlPathStr);
try { ... }
final int length = galleryArrList.size();
final String[] imagesStr = new String[length];
for (int i = 0; i < length; i++) {
final Map<String, String> map = galleryArrList.get(i);
imagesStr[i] = map.get(TAG_URL);
}
You might try using an ArrayList and add the URLs to the ArrayList within the for loop. When the loop is done, you can use the ArrayList.toArray(T[] array) method copy the URLs from the ArrayList to a String array.
ArrayList.toArray
ArrayList arlist = new ArrayList();
for (int i = 0; i < JSArrGallery.length(); i++) {
JSONObject galleryJO = JSArrGallery.getJSONObject(i);
idStr = galleryJO.getString(TAG_ID);
urlStr = galleryJO.getString(TAG_URL);
descrStr = galleryJO.getString(TAG_DESCR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String,String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, idStr);
map.put(TAG_URL, urlStr);
map.put(TAG_DESCR, descrStr);
galleryArrList.add(map);
arlist.add(urlStr);
}
// Create a String array to hold the URLs
String[] arUrls = new String[arlist.size()];
// Copy the URLs from the ArrayList to the String array
arlist.toArray(arUrls);
Supose i have name Mink,Mark,Aashis. How do compare them and arrange them according to alphabetical order. Collections.sort() dont work for me. Here i should have results Aashis,Mark and Mark.
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
Collections.sort( mylist, new Comparator<HashMap<String,String>>(){
public int compare(HashMap<String, String> lhs,
HashMap<String, String> rhs) {
//how do i compare string name
return 0;
}
});
Collections.sort(list, new Comparator(){
public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
return (o1.get("name")).compareToIgnoreCase(o2.get("name"));
}
Here "name" is the Key that you have provided at the time of insertion in the HashMap using put method.
EXTRA
If you want to parse double values then you can use the Double.parse() method.
return Double.compare(o1.get(value1), o1.get(value2));
NOTE - The nice thing about this approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.
Hope this will help you.
try this code
insert values
public ArrayList<HashMap<String, String>> list;
list = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 5; i++) {
HashMap<String, String> info = new HashMap<String, String>();
info.put("title", "gdfgdfgdfgdfggdfgfdgdgdgdffghfghfgh");
info.put("time", "44:55");
info.put("view", "54,353");
list.add(info);
}
get and compare
String title1 = ketan;
for (int i = 0; i < list.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map = list.get(i);
if(map.get("title")==title1);
{
........
......
}
}
I have JSONArray and when I decode JSON to HashMap at that time HashMap take last value of JSONArray.
here my code:
QjArray = new JSONArray(Questionresult);
JSONObject json_data = new JSONObject();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
json_data = QjArray.getJSONObject(i);
jQuestionName =json_data.getString("QuestionName");
objJMap.put("QuestionName",jQuestionName);
jQuestiontypeid = json_data.getInt("Questiontypeid");
String Qid = jQuestiontypeid.toString();
objJMap.put("Questiontypeid", Qid);
jAnswertypeid = json_data.getInt("Answertypeid");
String Aid = jAnswertypeid.toString();
objJMap.put("Answertypeid", Aid);
}
My JSONArray:
This is question list[{"QuestionID":"1","QuestionName":"when you come","Questiontypeid":"1","Answertypeid":"1"},{"QuestionID":"2","QuestionName":"about your words","Questiontypeid":"1","Answertypeid":"2"},{"QuestionID":"3","QuestionName":"you want extra service?","Questiontypeid":"1","Answertypeid":"3"},{"QuestionID":"4","QuestionName":"performance of quality ?","Questiontypeid":"1","Answertypeid":"4"},{"QuestionID":"5","QuestionName":"performance of staff?","Questiontypeid":"1","Answertypeid":"5"},{"QuestionID":"6","QuestionName":"when you left room ?","Questiontypeid":"2","Answertypeid":"1"},{"QuestionID":"7","QuestionName":"your words about roomservice ?","Questiontypeid":"2","Answertypeid":"2"},{"QuestionID":"8","QuestionName":"you like roomservice ?","Questiontypeid":"2","Answertypeid":"3"},{"QuestionID":"9","QuestionName":"performance room service ?","Questiontypeid":"2","Answertypeid":"4"},{"QuestionID":"10","QuestionName":"performance room service staff?","Questiontypeid":"2","Answertypeid":"5"}]
I think there are certain problems in your logic. For every JSON object u are creating new HashMap object inside for loop, so u will loose any previous data. Also HashMap will override new Data, so you will have only final data. What u can do is that create an arrayList of Hashmap....
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<STring, String>>();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
........
data.add(objJMap);
...}
This is because your code re initializes the HashMap after every loop.
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
....
}
Place the HashMap outside the loop and it will work fine.
objJMap = new HashMap<String, String>();
for (int i = 0; i<QjArray.length(); i++) {
....
}