androidandroid-bitmapsetbackground

Set Bitmap to my layout background


I'm downloading the image from URL and using this bitmap to my layout background. I can't able to see my image.

I'm struggle with this for past two days. Still now i cant able to find a solution. I have googled a lot. Please help me wrong misktake i done.

Thanks a lot in advance.

MY CODE:

Bitmap myImage = getBitmapFromURL("http://looksok.files.wordpress.com/2011/12/me.jpg");


        if (android.os.Build.VERSION.SDK_INT >= 16){
            setBackgroundV16Plus( myImage);
        }
        else{
            setBackgroundV16Minus( myImage);
        }

@TargetApi(16)
    private void setBackgroundV16Plus(  Bitmap bitmap) {
        linearLayout.setBackground(new BitmapDrawable(getApplicationContext().getResources(), bitmap));

    }

    @SuppressWarnings("deprecation")
    private void setBackgroundV16Minus(  Bitmap bitmap) {
        linearLayout.setBackgroundDrawable(new BitmapDrawable(bitmap));
    }

    public Bitmap getBitmapFromURL(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

Solution

  • private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
    
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
        }
    
        public LoadProfileImage() {
    
        }
    
        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap bitmap = null;
            try {
                InputStream in = new URL(urldisplay).openStream();
                bitmap = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.println(Log.ASSERT, "error", "" + e);
                e.printStackTrace();
            }
            return bitmap;
        }
    
        protected void onPostExecute(Bitmap result) {
         myImage=result;
        }
    }
    

    for calling method for downloading image

     new LoadProfileImage().execute("http://looksok.files.wordpress.com/2011/12/me.jpg");
    

    this statement to download image and store to your bitmap variable now set the background

    and add the Internet permission on manifest.