nazanin
nazanin

Reputation: 749

How to convert string json to url format in android

I'm trying to make a slider with this tutorial and it works very good. But when I try to get the image url from JSON with volley this url does not work. I want to convert the string to url, but my code is not working.

img1 = obj.getString("image_1");
URL myURL1 = new URL(img1);

Upvotes: 0

Views: 706

Answers (3)

Charitha Ratnayake
Charitha Ratnayake

Reputation: 379

Add app/gradle.app as a dependencies

compile 'com.google.code.gson:gson:2.6.2'

Now you need to create a Object.class according to your Json object. And all key names should same as your Object.class

Eg: Json object:

{
  "id": 1,
  "message": "This is example"
  "url": "http://www.jsoneditoronline.org/"
}

Class object:

public class ExampleObject {
    public long id;
    public String message;
    public String url;
}

Then in your Activity.java:

//jsonObj is your JSON object
ExampleObject obj = new Gson().fromJson(jsonObj, ExampleObject.class);

Now all the values are saved into your Object class.

Upvotes: 1

Danail Alexiev
Danail Alexiev

Reputation: 7772

The Android SDK contains a very useful Uri class. It exposes a Builder that can be used for property URL building (instead of string concatenation, that you are using). It also has a Uri.parse() method, that can create an instance from a String.

Upvotes: 0

thushcapone
thushcapone

Reputation: 162

If you want to load the url of the image retrieved in an imageview you can pass the string to an image processing library, for exemple Glide. Here's a good tutorial on how to set it up and use it: https://futurestud.io/tutorials/glide-getting-started.

Upvotes: 0

Related Questions