DiskLruCache - IllegalArgumentException

时间:2013-06-03 15:37:59

标签: android caching

我正在开发一款Android应用,我正在从服务器中提取一些图像/视频。我想缓存在磁盘上下载的信息但是当我试图将新数据放入缓存时发生错误并且我不知道为什么因为密钥似乎没问题。 这是堆栈跟踪:

    06-03 18:27:38.942: E/AndroidRuntime(10893): java.lang.IllegalArgumentException: keys must match regex [a-z0-9_-]{1,64}: "mYUb5gz5gx"
06-03 18:27:38.942: E/AndroidRuntime(10893):    at com.jakewharton.DiskLruCache.validateKey(DiskLruCache.java:633)
06-03 18:27:38.942: E/AndroidRuntime(10893):    at com.jakewharton.DiskLruCache.edit(DiskLruCache.java:421)
06-03 18:27:38.942: E/AndroidRuntime(10893):    at com.jakewharton.DiskLruCache.edit(DiskLruCache.java:416)
06-03 18:27:38.942: E/AndroidRuntime(10893):    at com.licenta.mementoapp.utils.DiskLruImageCache.put(DiskLruImageCache.java:69)
06-03 18:27:38.942: E/AndroidRuntime(10893):    at com.licenta.mementoapp.datafragments.PhotosFragment$1$1.done(PhotosFragment.java:92)

key =“mYUb5gz5gx”不匹配正则表达式吗?

2 个答案:

答案 0 :(得分:5)

不,它没有。您的密钥包含大写字母。只允许小写!

答案 1 :(得分:1)

您也可以使用MD5工具作为这样的MD5代码:

public static String hashKeyForDisk(String key) {
    String cacheKey;
    try {
        final MessageDigest mDigest = MessageDigest.getInstance("MD5");
        mDigest.update(key.getBytes());
        cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
        cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
}

private static String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            sb.append('0');
        }
        sb.append(hex);
    }
    return sb.toString();
}