Skip to content

Commit

Permalink
Convert ConcurrentHashMap to HashMap before seralizing to a file to a…
Browse files Browse the repository at this point in the history
…void a NotSerializableException
  • Loading branch information
davidgyoung committed Sep 14, 2017
1 parent 077c7a0 commit 5f18674
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
17 changes: 12 additions & 5 deletions src/main/java/org/altbeacon/beacon/service/MonitoringStatus.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
Expand Down Expand Up @@ -141,8 +142,7 @@ private Map<Region, RegionMonitoringState> getRegionsStateMap() {

private void restoreOrInitializeMonitoringStatus() {
long millisSinceLastMonitor = System.currentTimeMillis() - getLastMonitoringStatusUpdateTime();
mRegionsStatesMap = new ConcurrentHashMap<Region, RegionMonitoringState>() {
};
mRegionsStatesMap = new ConcurrentHashMap<Region, RegionMonitoringState>();
if (!mStatePreservationIsOn) {
LogManager.d(TAG, "Not restoring monitoring state because persistence is disabled");
}
Expand Down Expand Up @@ -180,10 +180,17 @@ protected void saveMonitoringStatusIfOn() {
try {
outputStream = mContext.openFileOutput(STATUS_PRESERVATION_FILE_NAME, MODE_PRIVATE);
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(getRegionsStateMap());

Map<Region,RegionMonitoringState> map = getRegionsStateMap();
// Must convert ConcurrentHashMap to HashMap becasue attempting to serialize
// ConcurrentHashMap throws a java.io.NotSerializableException
HashMap<Region,RegionMonitoringState> serializableMap = new HashMap<Region,RegionMonitoringState>();
for (Region region : map.keySet()) {
serializableMap.put(region, map.get(region));
}
objectOutputStream.writeObject(serializableMap);
} catch (IOException e) {
LogManager.e(TAG, "Error while saving monitored region states to file. %s ", e.getMessage());
LogManager.e(TAG, "Error while saving monitored region states to file ", e);
e.printStackTrace(System.err);
} finally {
if (null != outputStream) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;

import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.Region;
Expand All @@ -30,6 +31,7 @@
@RunWith(RobolectricTestRunner.class)
@Config(sdk = 18)
public class MonitoringStatusTest {
private static final String TAG = MonitoringStatusTest.class.getSimpleName();
@Before
public void before() {
org.robolectric.shadows.ShadowLog.stream = System.err;
Expand Down

0 comments on commit 5f18674

Please sign in to comment.