12

在我的 Android 应用程序中,我有这种采用 UUID 的方法。不幸的是,当我这样做时:

OverviewEvent overviewevent = eventAdapter.getOverviewEvent(UUID.fromString("0f14d0ab-9605-4a62-a9e4-5ed26688389b"));

我收到一条错误消息java.lang.IllegalArgumentException: Invalid UUID: 100

getOverviewEvent 的实现如下:

public OverviewEvent getOverviewEvent(UUID uuid) throws Exception {
    // Do stuff
}

有谁知道我该如何解决这个问题?

4

3 回答 3

18

这是避免使用此方法的解决方法,

String s = "0f14d0ab-9605-4a62-a9e4-5ed26688389b";
String s2 = s.replace("-", "");
UUID uuid = new UUID(
        new BigInteger(s2.substring(0, 16), 16).longValue(),
        new BigInteger(s2.substring(16), 16).longValue());
System.out.println(uuid);

印刷

0f14d0ab-9605-4a62-a9e4-5ed26688389b
于 2013-09-18T12:30:45.177 回答
1

你复制粘贴代码了吗,我发现有几个看起来正确的字符实际上是错误的 ACSII 代码。

删除 - 并再次更换它们。

我经常使用“”,因为不同的编辑器/计算机可能使用稍微不同的代码。

于 2020-03-17T13:23:58.577 回答
0

I had this problem too. I think this is because my Java version is low. I found that in my Android application, uuid.split("-") and uuid.replace("-") are both useless. I guess it may be caused by that Java regards "-" as a regular expression. However when I try uuid.split("\\-") and uuid.replace("\\-"), they didn't work either. I don't know why this happened. I think it's a bug of Java.

According to Fildor's comment, in Android's implementation, uuid.split("-") is used to split the uuid string into 5 parts. Then because of the mentioned bug, the uuid string couldn't be spliced into 5 parts. So "Invalid UUID" exception is thrown.

However, we can modify android's source code to avoid this problem. Using substring() method, we can split the uuid string into 5 parts. And then we can make the uuid.

The following codes worked for me:

public static UUID makeUuid(String uuidString) {
    String[] parts = {
            uuidString.substring(0, 7),
            uuidString.substring(9, 12),
            uuidString.substring(14, 17),
            uuidString.substring(19, 22),
            uuidString.substring(24, 35)
    };
    long m1 = Long.parseLong(parts[0], 16);
    long m2 = Long.parseLong(parts[1], 16);
    long m3 = Long.parseLong(parts[2], 16);
    long lsb1 = Long.parseLong(parts[3], 16);
    long lsb2 = Long.parseLong(parts[4], 16);
    long msb = (m1 << 32) | (m2 << 16) | m3;
    long lsb = (lsb1 << 48) | lsb2;
    return new UUID(msb, lsb);
}
于 2014-09-07T10:03:23.317 回答