I have a method in a class, which initialize a HashMap and put some keys and values inside it, then the method returns the HashMap. How can I retrieve the returned HashMap?
public Map<String, String> getSensorValue(String sensorName) {
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
And here I call this method from another class:
public static HashMap<String, String> sensValues = new HashMap<String, String>();
AllSensors sensVal = new AllSensors();
sensValues.putAll(sensVal.getSensorValue("orientation"));
String something = sensValues.get("x");
But it does not work in this way
sensValues.putAll(sensVal.getSensorValue("orientation"));
Makes my android application crash. The point is to retrive returned HashMap somehow.
HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Returns true if this map contains a mapping for the specified key. Returns true if this map maps one or more keys to the specified value.
It returns a reference.
put(key,value) is return type of 'value' in hashmap. put(key,value) where hashmap is defined as follows :- HashMap<Integer,String> hashmap = new HashMap<Integer,String>(); so return type of hashmap. put(key,value) is String,always .
You shouldn't have to copy the map. Just try using the returned reference:
Map<String, String> map = sensVal.getSensorValue("...");
Your method needs to return a Map<String,String>
. In the code you have posted, the Map
sensorValues is never initialized.
public Map<String, String> getSensorValue(String sensorName) {
Map<String,String> sensorValues = new HashMap<String,String>();
registerSensor(sensorName);
sensorValues.put("x","25");
sensorValues.put("y","26");
sensorValues.put("z","27");
return sensorValues;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With