Vaisakh N
Vaisakh N

Reputation: 790

Extract parameter values from url android

public static Hashtable parseUrlString(String url) {
    Hashtable parameter = new Hashtable();
    List<NameValuePair> params = null;
    try {
        params = URLEncodedUtils.parse(new URI(url), "UTF-8");
        for (NameValuePair param : params) {
            if (param.getName() != null && param.getValue() != null)
                parameter.put(param.getName(), param.getValue());
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return parameter;
}

The above method works for me to extract parameter name with value to a hashtable but in Api 21+ the NameValuePair and URLEncodedUtils is deprecated so what is the best way that I can replace this method?

Upvotes: 9

Views: 13581

Answers (5)

AITAALI_ABDERRAHMANE
AITAALI_ABDERRAHMANE

Reputation: 2519

try:

 Uri uri = Uri.parse(yourStrUrl);
 String paramValue = uri.getQueryParameter("yourParam");

Upvotes: 10

Ashish Rathee
Ashish Rathee

Reputation: 449

You can try ContentValues

for (ContentValues param : params) {
            if (param.getName() != null && param.getValue() != null)
                parameter.put(param.getName(), param.getValue());
        }

Upvotes: 0

Cheese Bread
Cheese Bread

Reputation: 2275

Already answered but here is the method written out

public static HashMap<String, String> getQueryString(String url) {
    Uri uri= Uri.parse(url);

    HashMap<String, String> map = new HashMap<>();
    for (String paramName : uri.getQueryParameterNames()) {
        if (paramName != null) {
            String paramValue = uri.getQueryParameter(paramName);
            if (paramValue != null) {
                map.put(paramName, paramValue);
            }
        }
    }
    return map;
}

Upvotes: 9

Laurentiu L.
Laurentiu L.

Reputation: 6686

You can use the android.net.Uri.

Uri uri=Uri.parse(url);

It has getQueryParameterNames() and uri.getQueryParameter(parameterNameString);

Upvotes: 12

BladeCoder
BladeCoder

Reputation: 12949

In Android, you should never use URLEncodedUtils which is now deprecated. A good alternative is to use the Uri class instead: retrieve the query parameter keys using getQueryParameterNames() then iterate on them and retrieve each value using getQueryParameter().

Upvotes: 13

Related Questions