我想通过遵循the wiki和this very helpful tutorial将HashMap保存到Android的内部存储中。我需要存储的HashMap的类型为HashMap<Int, Long
。 Int
存储id
毫秒,Long
存储epoch
毫秒。这是我的方法:
fun getNotificationsMap(context: Context): HashMap<Int, Long> {
val fis = context.openFileInput(Notifier.NOTIFICATIONS_MAP_FILE)!!
if (fis.isFileEmpty()) {
return hashMapOf()
}
val ois = ObjectInputStream(fis)
val map: HashMap<Int, Long> = ois.readObject() as HashMap<Int, Long>
ois.close()
return map
}
fun setNotificationOfId(id: Int, epoch: Long, context: Context) {
val fos = context.openFileOutput(
Notifier.NOTIFICATIONS_MAP_FILE, Context.MODE_PRIVATE
)!!
val oos = ObjectOutputStream(fos)
val updatedNotificationsMap = getNotificationsMap(context)
updatedNotificationsMap[id] = epoch
oos.writeObject(updatedNotificationsMap)
oos.close()
}
fun newNotificationId(context: Context): Int {
val notifications = getNotificationsMap(context)
val latestId = notifications.keys.max()
return if (latestId == null || latestId == 0)
Notifier.BASE_NOTIFICATION_ID_COUNT
else
latestId + 1
}
private fun FileInputStream.isFileEmpty(): Boolean {
val br = BufferedReader(InputStreamReader(this))
Log.i(TAG, "FileInput Stream is empty!")
return br.readLine() == null
}
当我致电getNotificationsMap(context)
时,出现以下错误:
java.util.concurrent.ExecutionException: java.io.EOFException
at androidx.work.impl.utils.futures.AbstractFuture.getDoneValue(AbstractFuture.java:516)
at androidx.work.impl.utils.futures.AbstractFuture.get(AbstractFuture.java:475)
at androidx.work.impl.WorkerWrapper$2.run(WorkerWrapper.java:289)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2344)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2813)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:301)
at com.jagoancoding.planyoursemester.util.DataUtil.getNotificationsMap(DataUtil.kt:70)
at com.jagoancoding.planyoursemester.util.DataUtil.newNotificationId(DataUtil.kt:88)
at com.jagoancoding.planyoursemester.util.Notifier$NotificationWorker.doWork(Notifier.kt:194)
at androidx.work.Worker$1.run(Worker.java:85)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
DataUtil.kt:70
所指的行
val ois = ObjectInputStream(fis)
所以我想知道如何正确地保存此哈希图?