Search code examples
androidbitmapandroid-image

android 4.1 image reading from url


Hi I am trying to get an image from url to bitmap. I have android 4.1 device. When I run this code on new URL(). open connection().getInputStream()); app freezes then force close. Any idea?

   runOnUiThread(new Runnable() {
            public void run() {
                String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium";
                try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
                            .openConnection().getInputStream());
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
              }

Solution

  • You are running network related operation on the ui thread using runOnUiThread.

    You should use a Thread or use Asynctask.

    http://developer.android.com/reference/android/os/AsyncTask.html

    You are probably getting NetworkOnMainThreadException

    http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

    Load asynctask on ui thread.

       new TheTask().execute().
    

    AsyncTask

      class TheTask extends AsyncTask<Void,Void,Void>
      {
    
    @Override
    protected Void doInBackground(Void... params) {
        // TODO Auto-generated method stub
                 String url = "http://netmera.com/cdn/app/file/netmera.com/series/img-48/1372262272227_89/medium"; 
        try {
                    Bitmap bmp = BitmapFactory.decodeStream(new URL(url)
                            .openConnection().getInputStream());
    
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } 
        return null;
    }
    
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }
    
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
    }
    

    Use runOnUiThread to update ui and do your netowrk related operation in doInbackground().

      runOnUiThread(new Runnable() //run on ui thread
                     {
                      public void run() 
                      { 
                         // update ui
                      }
                     });