0

I have that function with how I download images on my application, but I don't know why I've received that network on main thread exception. Here it's my class with function:

public class Tail {

String story, description, title, location;
int imageID;
URL url;

public URL getUrl() {
    return url;
}

public void setUrl(URL url) {
    this.url = url;
}

public Tail(int imageID, String location, String description, String title, String story) {
    this.imageID = imageID;
    this.location = location;
    this.title = title;
    this.description = description;
    this.story = story;
}

public Tail(String url, String location, String description, String title, String story) {
    try {
        this.url = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    this.location = location;
    this.title = title;
    this.description = description;
    this.story = story;
}

public String getStory() {
    return story;
}

public void setStory(String story) {
    this.story = story;
}


public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

public int getImageID() {
    return imageID;
}

public void setImageID(int imageID) {
    this.imageID = imageID;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public static Bitmap getImageBitmapFromUrl(URL url) {
    Bitmap bm = null;
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() != 200) {
            return bm;
        }
        conn.connect();
        InputStream is = conn.getInputStream();

        BufferedInputStream bis = new BufferedInputStream(is);
        try {
            bm = BitmapFactory.decodeStream(bis);
        } catch (OutOfMemoryError ex) {
            bm = null;
        }
        bis.close();
        is.close();
    } catch (Exception e) {
    }
    return bm;
}

Know anyone how can solve that problem?

Horatiu Dum
  • 31
  • 2
  • 7

1 Answers1

0

This exception is thrown when an application attempts to perform a networking operation on its main thread.

you need to perform HTTP connection in asynctask. have a look how to use assynctask http://developer.android.com/reference/android/os/AsyncTask.html

Jolson Da Costa
  • 1,095
  • 1
  • 12
  • 31