J-Y
J-Y

Reputation: 375

HttpConnection failing on .connect() for image URL

I'm trying to retrieve tweet information from a search query into my android application. I'm able to put the username and subject in the listview, but I have trouble grabbing the photo. Here is my GetView method from my adapter

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.listitem, null);
        }

        UserRecord user = users.get(position);
        if (user != null) {
            TextView username = (TextView) v.findViewById(R.id.username);
            TextView subject = (TextView) v.findViewById(R.id.subject);
            // Bitmap bitmap = DownloadImage(user.imageURL);
            ImageView img = (ImageView) v.findViewById(R.id.avatar);
            if (username != null) {
                username.setText(user.username);
            }

            if(subject != null) {
                subject.setText(user.subject);
            }

            if (img != null){
                try {
                    URL myURL = new URL(user.imageURL);
                    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    img.setImageBitmap(BitmapFactory.decodeStream(is));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return v;
    }

I traced through my code and it fails on conn.connect() and jumps to the catch statement. Does anyone know why this is happening? I have internet connection enabled in my mainfest. Thanks!

Upvotes: 0

Views: 51

Answers (2)

Hugo Pedrosa
Hugo Pedrosa

Reputation: 347

what is exception that is thrown and the error message?

Regards, Hugo Pedrosa

Upvotes: 0

Pragnani
Pragnani

Reputation: 20155

Yes, it will jump catch statement, and it will give you follwing Exceptions, 1.NetworkOnMainThreadException

2.NullPointerException

First one is because you are trying to perform network operation on UI Thread.

Second one is because your input stream is null, when you are trying to access it, you will get the NullPointerException.

What you need to do?

Use Separate thread or AsyncTask to download images

is it the best way?

You need to cache images when you showing images from url in listview, so try to use UniversalImageDownloader or LazyLoadList to populate images

Upvotes: 4

Related Questions