Url from string android

URL encoding in Android

How do you encode a URL in Android?

I thought it was like this:

If I do the above, the http:// in urlAsString is replaced by http%3A%2F%2F in encodedURL and then I get a java.net.MalformedURLException when I use the URL.

7 Answers 7

You don’t encode the entire URL, only parts of it that come from «unreliable sources».

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn’t throw checked exceptions.

Or use something like

I’m going to add one suggestion here. You can do this which avoids having to get any external libraries.

Give this a try:

You can see that in this particular URL, I need to have those spaces encoded so that I can use it for a request.

This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.

The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.

Источник

Parsing query strings on Android

On non-EE platforms, URL.getQuery() simply returns a string.

What’s the normal way to properly parse the query string in a URL when not on Java EE?

It is popular in the answers to try and make your own parser. This is very interesting and exciting micro-coding project, but I cannot say that it is a good idea.

The code snippets below are generally flawed or broken. Breaking them is an interesting exercise for the reader. And to the hackers attacking the websites that use them.

Parsing query strings is a well defined problem but reading the spec and understanding the nuances is non-trivial. It is far better to let some platform library coder do the hard work, and do the fixing, for you!

25 Answers 25

Since Android M things have got more complicated. The answer of android.net.URI.getQueryParameter() has a bug which breaks spaces before JellyBean. Apache URLEncodedUtils.parse() worked, but was deprecated in L, and removed in M.

So the best answer now is UrlQuerySanitizer . This has existed since API level 1 and still exists. It also makes you think about the tricky issues like how do you handle special characters, or repeated values.

The simplest code is

If you are happy with the default parsing behavior you can do:

but you should make sure you understand what the default parsing behavor is, as it might not be what you want.

On Android, the Apache libraries provide a Query parser:

If you have jetty (server or client) libs on your classpath you can use the jetty util classes (see javadoc), e.g.:

If you’re using Spring 3.1 or greater (yikes, was hoping that support went back further), you can use the UriComponents and UriComponentsBuilder :

components.getQueryParams() returns a MultiValueMap

For a servlet or a JSP page you can get querystring key/value pairs by using request.getParameter(«paramname»)

There are other ways of doing it but that’s the way I do it in all the servlets and jsp pages that I create.

On Android, I tried using @diyism answer but I encountered the space character issue raised by @rpetrich, for example: I fill out a form where username = «us+us» and password = «pw pw» causing a URL string to look like:

Читайте также:  Редактирование пдф для андроид

However, @diyism code returns «us+us» and «pw+pw» , i.e. it doesn’t detect the space character. If the URL was rewritten with %20 the space character gets identified:

This leads to the following fix:

Parsing the query string is a bit more complicated than it seems, depending on how forgiving you want to be.

First, the query string is ascii bytes. You read in these bytes one at a time and convert them to characters. If the character is ? or & then it signals the start of a parameter name. If the character is = then it signals the start of a paramter value. If the character is % then it signals the start of an encoded byte. Here is where it gets tricky.

When you read in a % char you have to read the next two bytes and interpret them as hex digits. That means the next two bytes will be 0-9, a-f or A-F. Glue these two hex digits together to get your byte value. But remember, bytes are not characters. You have to know what encoding was used to encode the characters. The character é does not encode the same in UTF-8 as it does in ISO-8859-1. In general it’s impossible to know what encoding was used for a given character set. I always use UTF-8 because my web site is configured to always serve everything using UTF-8 but in practice you can’t be certain. Some user-agents will tell you the character encoding in the request; you can try to read that if you have a full HTTP request. If you just have a url in isolation, good luck.

Anyway, assuming you are using UTF-8 or some other multi-byte character encoding, now that you’ve decoded one encoded byte you have to set it aside until you capture the next byte. You need all the encoded bytes that are together because you can’t url-decode properly one byte at a time. Set aside all the bytes that are together then decode them all at once to reconstruct your character.

Источник

Android: How store url in string.xml resource file?

I’m trying to store a fully qualified url, with also query params:

but it’s causing a problem because &reg is similar to ® entity and android tell me that and html entity is not well written.

I need this because every locale uses a fully different set of url query param.

I tried with [[CDATA[.. ]] but this syntax disliked by xml parser.

4 Answers 4

The problem is not with &req but with & itself. For XML/HTML you would have to use & entity (or & ), but for URLs you should rather URL-encode (see docs) strings, and in that case said & should be replaced with %26 . So your final string should look like:

Store it like this:

Where & is the XML equivelant of the ampersand symbol & .

Percent encoding may do the trick: http://en.wikipedia.org/wiki/Percent-encoding You’ll basically have something like this: www.miosito.net?prova%26reg=bis

You can enclose your url in double quotes, something like :

This is a recommended way to enclose string resources in Android.

Update 1 : Have a look at the following link for more info :

Update 2: @WebnetMobile.com : Correct, indeed 🙂 ‘&’ is being treated a special character by xml and enclosing in quotes doesn’t work. I tried out
www.miosito.net?prova%26reg=bis

and it didn’t work out either. I even tried enclosing it in quotes but still didn’t work. Am I missing something ?
Meanwhile, the following does work :

and then in code :

Resources resources=getResources();
String url=String.format(resources.getString(R.string.my_url),»?»,»&») ;

The ‘%1$s’ and ‘%2$s’ are format specifiers, much like what is used in printf in C. ‘%1$s’ is for strings, ‘%2$d’ is for decimal numbers and so on.

Источник

how to read value from string.xml in android?

I have written the line:

to get string value, but instead of returning string, it is giving me id of type integer. How can I get its string value? I mentioned the string value in the string.xml file.

18 Answers 18

UPDATE

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.

Читайте также:  Простой плеер для андроида без рекламы

If not in activity but have access to context:

By the way, it is also possible to create string arrays in the strings.xml like so:

And then from your Activity you can get the reference like so:

Only for future references.

You can use either getString(int) or getText(int) to retrieve a string. getText(int) will >retain any rich text styling applied to the string.

In fragments, you can use

If you want to add the string value to a button for example, simple use

The defined text in strings.xml looks like this:

You must reference Context name before using getResources() in Android.

You can use this code:

Basically, you need to pass the resource id as a parameter to the getText() method.

If you are in an activity you can use

If you are not in an Activity use this :

Details

  • Android Studio 3.1.4
  • Kotlin version: 1.2.60
  • single line use
  • minimum code
  • use suggestions from the compiler

Step 1. Application()

Get link to the context of you application

Step 2. Add int extension

Usage

Results

while u write R . you are referring to the R.java class created by eclipse, use getResources().getString() and pass the id of the resource from which you are trying to read inside the getString() method.

Example : String[] yourStringArray = getResources().getStringArray(R.array.Your_array);

You can read directly the value defined into strings.xml:

and set into a variable:

but we can define the string into the view:

I hope this code is beneficial

Update

  • You can use getString(R.string.some_string_id) in both Activity or Fragment .
  • You can use Context.getString(R.string.some_string_id) where you don’t have direct access to getString() method. Like Dialog .

Problem is where you don’t have Context access, like a method in your Util class.

Assume below method without Context.

Now you will pass Context as a parameter in this method and use getString().

What i do is

What? It is very simple to use anywhere in your app!

So here is a Bonus unique solution by which you can access resources from anywhere like Util class .

Источник

How can I open a URL in Android’s web browser from my application?

How to open an URL from code in the built-in web browser rather than within my application?

but I got an Exception:

40 Answers 40

That works fine for me.

As for the missing «http://» I’d just do something like this:

I would also probably pre-populate your EditText that the user is typing a URL in with «http://».

A common way to achieve this is with the next code:

that could be changed to a short code version .

the shortest! :

Simple Answer

How it works

Please have a look at the constructor of Intent :

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it’s safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

In 2.3, I had better luck with

The difference being the use of Intent.ACTION_VIEW rather than the String «android.intent.action.VIEW»

or if you want then web browser open in your activity then do like this:

and if you want to use zoom control in your browser then you can use:

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

Just like the solutions other have written (that work fine), I would like to answer the same thing, but with a tip that I think most would prefer to use.

Читайте также:  Настройка русского языка android

In case you wish the app you start to open in a new task, indepandant of your own, instead of staying on the same stack, you can use this code:

There is also a way to open the URL in Chrome Custom Tabs . Example in Kotlin :

other option In Load Url in Same Application using Webview

The Kotlin answer:

I have added an extension on Uri to make this even easier

As a bonus, here is a simple extension function to safely convert a String to Uri.

You can also go this way

In Manifest dont forget to add internet permission.

Webview can be used to load Url in your applicaion. URL can be provided from user in text view or you can hardcode it.

Also don’t forget internet permissions in AndroidManifest.

Within in your try block,paste the following code,Android Intent uses directly the link within the URI(Uniform Resource Identifier) braces in order to identify the location of your link.

You can try this:

A short code version.

Simple and Best Practice

Method 1:

Method 2:

So I’ve looked for this for a long time because all the other answers were opening default app for that link, but not default browser and that’s what I wanted.

I finally managed to do so:

BTW, you can notice context .whatever, because I’ve used this for a static util method, if you are doing this in an activity, it’s not needed.

The response of MarkB is right. In my case I’m using Xamarin, and the code to use with C# and Xamarin is:

Chrome custom tabs are now available:

The first step is adding the Custom Tabs Support Library to your build.gradle file:

And then, to open a chrome custom tab:

Simple, website view via intent,

use this simple code toview your website in android app.

Add internet permission in manifest file,

Based on the answer by Mark B and the comments bellow:

android.webkit.URLUtil has the method guessUrl(String) working perfectly fine (even with file:// or data:// ) since Api level 1 (Android 1.0). Use as:

In the Activity call:

Check the complete guessUrl code for more info.

Simply go with short one to open your Url in Browser:

That error occurred because of invalid URL, Android OS can’t find action view for your data. So you have validate that the URL is valid or not.

Short & sweet Kotlin helper function:

A new and better way to open link from URL in Android 11.

I checked every answer but what app has deeplinking with same URL that user want to use?

Today I got this case and answer is browserIntent.setPackage(«browser_package_name»);

I think this is the best

Put below code into global class

This way uses a method, to allow you to input any String instead of having a fixed input. This does save some lines of code if used a repeated amount of times, as you only need three lines to call the method.

Using this method makes it universally usable. IT doesn’t have to be placed in a specific activity, as you can use it like this:

Or if you want to start it outside an activity, you simply call startActivity on the activity instance:

As seen in both of these code blocks there is a null-check. This is as it returns null if there is no app to handle the intent.

This method defaults to HTTP if there is no protocol defined, as there are websites who don’t have an SSL certificate(what you need for an HTTPS connection) and those will stop working if you attempt to use HTTPS and it isn’t there. Any website can still force over to HTTPS, so those sides lands you at HTTPS either way

Because this method uses outside resources to display the page, there is no need for you to declare the INternet permission. The app that displays the webpage has to do that

Источник

Оцените статью