Searches the query string for parameter values with the given key. - Android Network

Android examples for Network:Uri

Description

Searches the query string for parameter values with the given key.

Demo Code


//package com.java2s;
import android.net.Uri;
import java.util.ArrayList;
import java.util.Collections;

import java.util.List;

public class Main {
    /**/* ww w  .  ja v a2s  .c om*/
     * Searches the query string for parameter values with the given key.
     *
     * @param key which will be encoded
     * @return a list of decoded values
     * @throws UnsupportedOperationException if this isn't a hierarchical URI
     * @throws NullPointerException          if key is null
     */
    public static List<String> getQueryParameters(Uri uri, String key) {
        if (uri.isOpaque()) {
            return Collections.emptyList();
        }
        if (key == null) {
            throw new NullPointerException("key");
        }

        String query = uri.getEncodedQuery();
        if (query == null) {
            return Collections.emptyList();
        }

        ArrayList<String> values = new ArrayList<String>();

        int start = 0;
        do {
            int nextAmpersand = query.indexOf('&', start);
            int end = nextAmpersand != -1 ? nextAmpersand : query.length();

            int separator = query.indexOf('=', start);
            if (separator > end || separator == -1) {
                separator = end;
            }

            if (separator - start == key.length()
                    && query.regionMatches(start, key, 0, key.length())) {
                if (separator == end) {
                    values.add("");
                } else {
                    values.add(query.substring(separator + 1, end));
                }
            }

            // Move start to end of name.
            if (nextAmpersand != -1) {
                start = nextAmpersand + 1;
            } else {
                break;
            }
        } while (true);

        return Collections.unmodifiableList(values);
    }
}

Related Tutorials