mesopotamia mesopotamia - 3 months ago 18
Android Question

HashMap dont stay stable in android

Hi I am trying to save a object in HashMap if it is not exist than if it is exsit I want to control its value with new data. If data change than I want to do sth. else. But whenever I tried to compare new data and hash value I saw they are same on every time . How can I handle with this issue. There is code:

BluetoothLeDevice deviceLe;
private Map<String, byte[]> mMacMap;
byte [] integer0 =new byte[4];
byte[] tempInteger0=new byte[4];

public void addSensor(String macId, BluetoothLeDevice deviceLe) {
byte [] addSensorrecord=deviceLe.getScanRecord();
int j=0;
for(int i=15;i<19;i++)
{
integer0 [j]=addSensorrecord[i];
j++;
}
if (mMacMap.containsKey(macId)) {
tempInteger0 = mMacMap.get(macId);

if(!integer0 .equals(tempInteger0))
{
mMacMap.remove(macId);
mMacMap.put(macId, integer0 );
new SendBLEData().execute(deviceLe);
}

} else {
final byte [] LocalInteger0=new byte[4];
int t=0;
for(int i=15;i<19;i++)
{
LocalInteger0[t]=addSensorrecord[i];
t++;
}
mMacMap.put(macId, LocalInteger0);
new SendBLEData().execute(deviceLe);
}
}

Answer

Just a few additions to the already posted answers.

The remove below is not necessary, a simple put will replace the old value

mMacMap.remove(macId);
mMacMap.put(macId, integer0 );

From the javadoc

If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Have you considered making bytes 15-19 into a string and adding them onto the maps key? This would eliminate the array compare and make the lookups much faster.