Question

I'm trying to change a view's background image dynamically. I have a paintView class which extends View class. I take in a user input(m_text in the code below) which is a filename of an image saved in a sdcard. Then, I want to set it as the background image of the paintView.

I tried but it only gives me a white background. So I thought that there could be something wrong with the path. So I commented out the part where I used user input and tried using the actual path of the image (the path I used to save the image, uncommented address in the code below). It still gives me a white background.

Can someone please help me finding where the error is?

Thanks!

@SuppressWarnings("deprecation")
private void loadImage(){

    String root = Environment.getExternalStorageDirectory().toString();
    //String address = root + m_text;
    String address = "file://" + root + "/saved_images" + "/Image.jpg";
    File imageFile = new File(address);

    Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
    System.out.println(imageFile.getAbsolutePath());
    Drawable bgImage = new BitmapDrawable(context.getResources(), bitmap);

    paintView.setBackgroundDrawable(bgImage);

}

and this is where this function is being called. It's within onCreate method:

loadButton.setOnClickListener(new OnClickListener(){

           @Override
           public void onClick(View arg0){
               AlertDialog.Builder builder = new AlertDialog.Builder(context);

               final EditText input = new EditText(context);
               input.setInputType(InputType.TYPE_CLASS_TEXT);
               builder.setView(input);

               builder.setPositiveButton("load", new DialogInterface.OnClickListener(){
                   @Override
                   public void onClick(DialogInterface dialog, int which){
                       m_text = input.getText().toString();
                       loadImage();
                   }
               });

               builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
                   @Override
                   public void onClick(DialogInterface dialog, int which){
                       dialog.cancel();
                   }
               });


               builder.show();

           }       
        });

In the Manifest:

<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
Was it helpful?

Solution

why did you use this?

String address = "file://" + root + "/saved_images" + "/Image.jpg";

I think you cannot decode the file. Have you checked your bitmap? I think you just need to use

String address = root + "/saved_images" + "/Image.jpg";

Have a try.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top