Groot
Groot

Reputation: 493

Android - Unhandled java.net.MalformedURLException

I'm getting a MalformedURLException some code in my Android Studio project. My aim is to get and display an image from a web page, and the URL seems to be fine, but it's giving me this error.

I have already put the code in a try,catch, but that is still giving me the error. Here is the code to grab the image and display it:

    try
    {
        url = new URL(items.get(position).getLink());
        bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
    }
    catch (IOException e)
    {
        throw new RuntimeException("Url Exception" + e);
    }

    holder.itemTitle.setText(items.get(position).getTitle());;
    holder.itemHolder.setBackgroundDrawable(new BitmapDrawable(bmp));

items.get(position).getLink() is meant to get the link that is being displayed in a ListView, but even something like URL url = new URL("https://www.google.com") doesn't work.

Thanks.

Upvotes: 0

Views: 5316

Answers (3)

K Priyanka
K Priyanka

Reputation: 9

Just click alt+enter and then import try catch section... this helped me...

Upvotes: 0

ashoke
ashoke

Reputation: 6461

your url is formatted without the protocol at the beginning try

url = new URL("http://"+items.get(position).getLink());

sometimes the url string may have special characters, in which case you need to encode it properly please see this. And also, the url you posted in the comment is not an image.

Upvotes: 1

Aakash Gandhi
Aakash Gandhi

Reputation: 253

it is exception beacuse of url class

add antoher catch like

catch (MalformedURLException e) {

            e.printStackTrace();
        }

Upvotes: 0

Related Questions