greywolf82 greywolf82 - 5 months ago 47
Android Question

Lvl library and android marshmallow

Lvl library doesn't compile anymore on Android Marshmallow due to the lack apache stuff removed. You can add 'useLibrary 'org.apache.http.legacy'' but it's only a temporary workaround. The problem is this method:

private Map<String, String> decodeExtras(String extras) {
Map<String, String> results = new HashMap<String, String>();
try {
URI rawExtras = new URI("?" + extras);
List<NameValuePair> extraList = URLEncodedUtils.parse(rawExtras,
"UTF-8");
for (NameValuePair item : extraList) {
results.put(item.getName(), item.getValue());
}
} catch (URISyntaxException ignored) {
}
return results;
}


NameValuePair
and
URLEncodedUtils
are not found. What is the new "way"? How can I replace this call with new code compliant with the new Android version?

Answer

I wrote my own class looking at the original code as temporary workaround:

public class URLUtils {
    private static final String PARAMETER_SEPARATOR = "&";
    private static final String NAME_VALUE_SEPARATOR = "=";
    private static final String DEFAULT_CONTENT_CHARSET = "ISO-8859-1";

    public static List<Item> parse(final URI uri, final String encoding) {
        List<Item> result = Collections.emptyList();
        final String query = uri.getRawQuery();
        if (query != null && query.length() > 0) {
            result = new ArrayList<>();
            parse(result, new Scanner(query), encoding);
        }
        return result;
    }

    public static void parse(final List<Item> parameters, final Scanner scanner, final String encoding) {
        scanner.useDelimiter(PARAMETER_SEPARATOR);
        while (scanner.hasNext()) {
            final String[] nameValue = scanner.next().split(NAME_VALUE_SEPARATOR);
            if (nameValue.length == 0 || nameValue.length > 2)
                throw new IllegalArgumentException("bad parameter");

            final String name = decode(nameValue[0], encoding);
            String value = null;
            if (nameValue.length == 2)
                value = decode(nameValue[1], encoding);
            parameters.add(new Item(name, value));
        }
    }


    private static String decode (final String content, final String encoding) {
        try {
            return URLDecoder.decode(content, encoding != null ? encoding : DEFAULT_CONTENT_CHARSET);
        } catch (UnsupportedEncodingException problem) {
            throw new IllegalArgumentException(problem);
        }
    }
}

public class Item {
    private String name;
    private String value;

    public Item(String n, String v) {
        name = n;
        value = v;
    }

    public String getName() {
        return name;
    }

    public String getValue() {
        return value;
    }
}