I'm getting multiple values from an ArrayList and saving them in a variable:
For each code:
static ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
for (RoomHandler roomHandler : roomHandlerArrayList) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(ROOM_ID, Integer.toString(roomHandler.getRoomID()));
item.put(ROOM_NAME, roomHandler.getRoomName());
test.add(item);
}
And I'm calling these variables on my adapter. But when I try to print both variables, I only get the ROOM_NAME variable, when I print the ROOM_ID, I get the ROOM_NAME value, which it means that the last value is being recorded twice.
Adapter code:
String getRoomName = (String) ((Map) getItem(position))
.get(RoomsActivity.ROOM_NAME);
String getRoomID = (String) ((Map) getItem(position))
.get(RoomsActivity.ROOM_ID);
roomName.setText(getRoomName + getRoomID); //prints ROOM_NAME + ROOM_NAME
What am I doing wrong?
Related
I am trying to compare two ArrayList< Map< String, Object>> objects but the problem is that I need to compare them in different app sessions. So I am saving the first ArrayList in SharedPreferences after converting it to String using Gson. Then I query the string in next session to compare it. I tried converting it back to ArrayList then comparing it with the list generated during the new session. Also tried converting the new list into json and then comparing both texts. But the result is same. Below is the relevant code:
Declaration:
ArrayList<Map<String, Object>> tweetMapArray = new ArrayList<>();
Then in some method :
List<twitter4j.Status> statuses = twitter.getUserTimeline(params[0], new Paging(1, 200));
tweetMapArray.clear(); // I am also reusing it
for (twitter4j.Status status : statuses) {
Map<String, Object> valuesToPutInMarker = new HashMap<>();
valuesToPutInMarker.put("id", status.getId());
valuesToPutInMarker.put("status", status.getText());
tweetMapArray.add(valuesToPutInMarker);
}
Now saving tweetMapArray in SharedPreferences:
String jsonStr = gson.toJson(tweetMapArray);
editor = configData.edit();
editor.putString("tweetData", jsonStr);
editor.apply();
Querying data:
private boolean seeIfTheDataIsNew() {
String dataFromSharedPreferences = configData.getString("tweetData", null);
Type collectionType2 = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> oldTweets = gson.fromJson(dataFromSharedPreferences, collectionType2);
String jsonStr = gson.toJson(tweetMapArray);
return jsonStr.equalsIgnoreCase(dataFromSharedPreferences);
// OR
return !(oldTweets.containsAll(tweetMapArray) && tweetMapArray.containsAll(oldTweets));
}
Here, both methods in last two lines return true. In the testing sample, they should return false.
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 have this arraylist and another for hashmap
ArrayList<HashMap<String, String>> agentList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> agentproperty = new HashMap<String, String>();
I have received jArray from php file. and trying to put it in the array using hashmap.
JSONArray jArray = jsonObj.getJSONArray(TAG_AGENT);
String id = null;
String name = null;
for (int i = 0; i < jArray.length(); i++) {
JSONObject a = jArray.getJSONObject(i);
id = a.getString(TAG_AGENTID);
name = a.getString(TAG_NAME);
agentproperty.put("AGENTID", id);
agentproperty.put("NAME", name);
Log.d("id",id);
Log.d("name",name);
agentList.add(agentproperty);
}
Log.d("firstperson",String.valueOf(agentList.get(0)));
Log.d("secondperson",String.valueOf(agentList.get(1)));
I can get
id 1, hame cathy; id 2, name john
for the log inside loop. But from the last log, I am getting
id 2, name john; id 2, name john
It seems the value of agentproperty is changed even after adding in arraylist.
I tried taking the agentList.add(agentproperty); outside of loop. Didnt work. Only inserts the last value (id 2, name john). Any idea how can i populate this array with all the values I get from loop. I will need to use agentList in listview.
yes it is. You have to create a new instance of the HashMap at every iteration, otherwise you will override the value for a given key, if an entry already exists
Move
HashMap<String, String> agentproperty = new HashMap<String, String>();
inside the for loop
Okay so I have spent several hours trying to wrap my head around this concept of a HashMap in Java but am just not able to figure it out. I have looked at many tutorials but none seem to address my exact requirement and I cannot get it to work.
I am trying to create an associative multi dimensional array in Java (or something similar) so that I can both save to and retrieve from the array with keys that are Strings.
This is how I would do it in PHP and explains it best what I am trying to do:
//loop one - assign the names
myArray['en']['name'] = "english name";
myArray['fr']['name'] = "french name";
myArray['es']['name'] = "spanish name";
//loop two - assign the description
myArray['en']['desc'] = "english description";
myArray['fr']['desc'] = "french description";
myArray['es']['desc'] = "spanish description";
//loop three - assign the keywords
myArray['en']['keys'] = "english keywords";
myArray['fr']['keys'] = "french keywords";
myArray['es']['keys'] = "spanish keywords";
//later on in the code be able to retrive any value similar to this
english_name = myArray['en']['name'];
french_name = myArray['fr']['name'];
spanish_name = myArray['es']['name'];
This is what I tried in Java but it is not working:
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
myArray.put("en" , put("name", "english name")); //gives me "cannot find symbol" at second put
myArray.put("en" , ("name", "english name")); //gives me "')' expected" after second comma
So I am sure its something simple that I am missing but please point it out because this is very frustrating!
Thanks
EDIT:
So here is some working code on how I implemented the answer I accepted:
import java.util.*;
HashMap<String, HashMap<String, String>> finalArray = new HashMap<String, HashMap<String, String>>();
String[] langArray = {"en","fr","de","no","es"};
//Initialize each language key ahead of time
for(String lang : langArray) { // foreach lang in langArray
if (!finalArray.containsKey(lang)) {
finalArray.put(lang, new HashMap<String, String>());
}
}
//loop one - assign names
for(String lang : langArray) {
String theName = lang + " name"; //go get the name from somewhere
finalArray.get(lang).put("name", theName);
}
//loop two - assign description
for(String lang : langArray) {
String theDesc = lang + " description"; //go get the description from somewhere
finalArray.get(lang).put("desc", theDesc);
}
//loop three - assign keywords
for(String lang : langArray) {
String theKeys = lang + " keywords"; //go get the keywords from somewhere
finalArray.get(lang).put("keys", theKeys);
}
//display output
for(String lang : langArray) {
System.out.println("LANGUAGE: " + lang);
System.out.println(finalArray.get(lang).get("name"));
System.out.println(finalArray.get(lang).get("desc"));
System.out.println(finalArray.get(lang).get("keys"));
}
//example to retrieve/get values
String english_name = finalArray.get("en").get("name");
String french_desc = finalArray.get("fr").get("desc");
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
if (!myArray.containsKey("en")) {
myArray.put("en", new HashMap<String, String>());
}
myArray.get("en").put("name", "english name");
In Java you have to be explicit about when you are creating an object. In this case first we check if there is already a HashMap object stored in our outer HashMap under the key "en". If not, we create an empty one.
Now to put a new value into it we have to first get it from the outer HashMap, then put the new value.
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> value = new HashMap<String, String>();
value.put("name", "English name");
value.put("desc", "English description");
value.put("keys", "English keywords");
myArray.put("en" , value);
value = new HashMap<String, String>();
value.put("name", "French name");
value.put("desc", "French description");
value.put("keys", "French keywords");
myArray.put("fr" , value);
Unfortunately, there's no concise syntax for constructing populated maps in Java. You'll have to write it out long-hand. A separate helper method can make it a little simpler:
HashMap<String, String> makeMap(String name, String desc, String keys) {
HashMap<String, String> map = new HashMap<>();
// Before Java 7, above must be: new HashMap<String, String>();
map.put("name", name);
map.put("desc", desc);
map.put("keys", keys);
}
Then:
HashMap<String, HashMap<String, String>> myArray = new HashMap<>();
myArray.put("en",
makeMap("english name", "english description", "english keywords"));
// etc.
You would retrieve it with:
english_name = myArray.get("en").get("name");
import java.util.HashMap;
public class Main
{
public static void main(String[] args) {
// Creating array
HashMap<String, HashMap<String, String>> myArray = new HashMap<String, HashMap<String, String>>();
// Setting values
for(int i=0; i<100;i++) {
myArray.put("key1"+i, new HashMap<String, String>());
myArray.get("key1"+i).put("key2"+i, "value"+i);
}
// Getting values
for(int i=0; i<100; i++) {
System.out.println(myArray.get("key1"+i).get("key2"+i));
}
}
}
I really liked the example by "dAv dEv", though he didn't really fill his double array of keys (I added a loop within a loop). I also like TreeMaps better than HashMaps because they aren't as random.
import java.util.Map;
import java.util.TreeMap;
TreeMap<String, TreeMap<String, String>> myArray =
new TreeMap<String, TreeMap<String, String>>();
String[] roles = { "Help Desk", "Administrator", "Super Use", ... };
String[] elements = { "Hydrogen", "Helium", "Lithium", "Beryllium", ... };
// Setting values TODO: read data values from Excel spreadsheet (or wherever)
for(String role : roles) {
myArray.put(role, new TreeMap<String, String>());
for (String elementName : elements) {
String value = Utils.getHumanName("first", true);
myArray.get(role).put(elementName, value);
}
}
// Getting values
for (Map.Entry<String,TreeMap<String,String>> entry1 : myArray.entrySet()) {
String key1 = entry1.getKey();
TreeMap<String,String> value1 = entry1.getValue();
for (Map.Entry<String,String> entry2 : value1.entrySet()) {
String key2 = entry2.getKey();
String value2 = entry2.getValue();
System.out.println("(" + key1 + ", " + key2 + ") = " +
myArray.get(key1).get(key2));
}
}
P.S. I used Utils.getHumanName() as my data generator. You will need to use your own.
My ArrayList<HashMap<String, String>> songslist has no values in it. In my doInBackground method i have for-loop that should fill this ArrayList. The Strings "id", "interpret"... have also values in it. Where is the problem? Here the code:
JSONArray charts = json.getJSONArray(TAG_CHARTS);
// looping through All Products
for(int i=0;i<charts.length();i++) {
JSONObject json_data = charts.getJSONObject(i);
String id = json_data.getString(TAG_ID);
String interpret = json_data.getString(TAG_INTERPRET);
String titel = json_data.getString(TAG_TITEL);
String album = json_data.getString(TAG_ALBUM);
String albumcover = json_data.getString(TAG_ALBUMCOVER);
String likes = json_data.getString(TAG_LIKES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_INTERPRET, interpret);
map.put(TAG_TITEL, titel);
map.put(TAG_ALBUM, album);
map.put(TAG_ALBUMCOVER, albumcover);
map.put(TAG_LIKES, likes);
songslist.add(map);
}
but List is empty. The JSONArray includes the values.
The code that creates the map and puts the elements in the list is ok. So its either
1) songslist is messed up. You don't show where/how its created
2) you think charts has items in it, but it doesn't.
You're not entering into the loop. Your posted code its OK. charts.length() == 0