Search code examples
androidcontent-values

How to encode and append ContentValue values into an URL


Earlier when NameValuePairs were available directly it was easy to encode and append URL variables using:

String UrlString = URLEncodedUtils.format(nameValuePairs, "utf-8");

But now they have been deprecated I moved onto using ContentValues for storing name-value pairs.

What I want to ask that is there an easy and straight way to encode and append ContentValue values into an URL like it was possible with NameValuePairs or else how to do it?


Solution

  • What I want to ask that is there an easy and straight way to encode and append ContentValue values into an URL like it was possible with NameValuePairs or else how to do it?

    If it's query parameters you're referring to, it's probably best to have a look at Uri. In particular, its Builder provides various methods to set or append path segments, query parameters (either pre-encoded or not) and the like. Encoding values is also supported through the static Uri.encode() helpers.

    That being said, if you need a simple drop-in replacement for the formatting options provided by URLEncodedUtils, it would be pretty straightforward to take its source code and make it compatible with ContentValues (or a Map<String, Object> for that matter, since ContentValues is little more than a thin wrapper around that).

    I've set up a quick (and untested) gist for this. Feel free to use it as a starting point, and - by all means - fix any mistakes I may have made.