0
votes

In my app, I have a imageView that collects the a picture from the user, saves it, and then is supposed to set that image as the background in my other activity. I can't figure out where to set the image as the background in my activity using this code:

Drawable d = new BitmapDrawable(getResources(),bitmap);
yourBackgroundView.setBackground(d);

Here is the coding: Drag_and_Drop_App.java:

package com.example.awesomefilebuilderwidget;

IMPORTS

public class Drag_and_Drop_App extends Activity {
private ListView mListAppInfo;
// Search EditText
EditText inputSearch;
public static AppInfoAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // set layout for the main screen
    setContentView(R.layout.drag_and_drop_app);
    // import buttons
    Button btnLinkToFeedback = (Button) findViewById(R.id.btnLinkToFeedback);
    Button btnLinkToPersonalize = (Button) findViewById(R.id.btnLinkToPersonalize);

    // Link to Feedback Screen
    btnLinkToFeedback.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    Feedback.class);
            startActivity(i);
            finish();
        }
    });

    // Link to Personalize Screen
    btnLinkToPersonalize.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    Personalize.class);
            startActivity(i);
            finish();
        }
    });

    // create new adapter
    adapter = new AppInfoAdapter(this, (List<ApplicationInfo>)  Utilities.getInstalledApplication(this), getPackageManager());
    // load list application
   mListAppInfo = (ListView)findViewById(R.id.lvApps);
    // set adapter to list view
    mListAppInfo.setAdapter(adapter);
    // search bar
    inputSearch = (EditText) findViewById(R.id.inputSearch);

    inputSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            // When user changed the Text
            // Drag_and_Drop_App.this.adapter.getFilter().filter(cs);  
             if (Drag_and_Drop_App.this.adapter == null){
                 // some print statement saying it is null
                 Log.d ("msg_error", "adapter_is_null");
             }
                Drag_and_Drop_App.this.adapter.getFilter().filter(cs);

            }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub                          
        }
        });


    // implement event when an item on list view is selected
    mListAppInfo.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
            // get the list adapter
            AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
            // get selected item on the list
            ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
            // launch the selected application
            Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
        }

    });

    // implement event when an item on list view is selected via long-click for drag and drop
    mListAppInfo.setOnItemLongClickListener(new OnItemLongClickListener(){

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                int pos, long id) {
            // TODO Auto-generated method stub
            // get the list adapter
            AppInfoAdapter appInfoAdapter = (AppInfoAdapter)parent.getAdapter();
            // get selected item on the list
            ApplicationInfo appInfo = (ApplicationInfo)appInfoAdapter.getItem(pos);
            // launch the selected application
            Utilities.launchApp(parent.getContext(), getPackageManager(), appInfo.packageName);
            return true;
        }


    });

}
// load image from imageview
public Bitmap getThumbnail(String filename) {
       Bitmap thumbnail = null;
       try {
          File filePath = this.getFileStreamPath(filename);
          FileInputStream fi = new FileInputStream(filePath);
          thumbnail = BitmapFactory.decodeStream(fi);
       } catch (Exception ex) {
       Log.e("getThumbnail() on internal storage", ex.getMessage());
       }
       return thumbnail;
    }

}

Added coding:

        RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.layout.drag_and_drop_app);
    yourBackgroundView = backgroundReference.get();

    Drawable d = new BitmapDrawable(getResources(),bitmap);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
            yourBackgroundView.setBackgroundDrawable(d);
        } else {
            yourBackgroundView.setBackground(d);
        }

CURRENT CLASSES THAT ARE RELEVANT:

Personalize.java:

package com.example.awesomefilebuilderwidget;

IMPORTS

public class Personalize extends Activity implements OnClickListener {
Button button;
ImageView image;
ImageView image2;
Button btnChangeImage;
Button btnChangeImageForIcon;
private static final int SELECT_PICTURE = 1;
private static final int SELECT_PICTURE_2 = 2;
private String  selectedImagePath;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalize);

image = (ImageView) findViewById(R.id.imageView1);
image2 = (ImageView) findViewById(R.id.imageView2Icon);

Button btnChangeImage = (Button) findViewById(R.id.btnChangeImage);    
btnChangeImage.setOnClickListener(this);
Button btnChangeImageForIcon = (Button) findViewById(R.id.btnChangeImageForIcon); 
btnChangeImageForIcon.setOnClickListener(this);

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
 Intent intent = new Intent();
 intent.setType("image/*");
 intent.setAction(Intent.ACTION_GET_CONTENT);
 intent.addCategory(Intent.CATEGORY_OPENABLE);
 startActivityForResult(intent, SELECT_PICTURE);


};

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE)
{
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    Bitmap b1 = getAndDecodeImage(selectedImagePath);
    if(b1 != null){
        image.setImageBitmap(b1);
    }           
} else if (requestCode == SELECT_PICTURE_2)
{
    Uri selectedImageUri = data.getData();
    selectedImagePath = getPath(selectedImageUri);
    Bitmap b2 = getAndDecodeImage(selectedImagePath);
    if(b2 != null){
        image2.setImageBitmap(b2);
    }
}    
}
}

private Bitmap getAndDecodeImage(String  selectedImagePath){
try {
    FileInputStream fileis=new FileInputStream(selectedImagePath);
    BufferedInputStream bufferedstream=new BufferedInputStream(fileis);
    byte[] bMapArray= new byte[bufferedstream.available()];
    bufferedstream.read(bMapArray);
    Bitmap bMap = BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);

    if (fileis != null) 
    {
        fileis.close();
    }
    if (bufferedstream != null) 
    {
        bufferedstream.close();
    }
    return bMap;
} catch (FileNotFoundException e) {                 
    e.printStackTrace();
} catch (IOException e) {                   
    e.printStackTrace();
}   
return null;
}

public boolean saveImageToInternalStorage(Bitmap image) { try { FileOutputStream fos = this.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE); image.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close();
return true; } catch (Exception e) { return false; } } }

1

1 Answers

2
votes

Not sure what type of layout you're using, but you'd have to give the layout where you want to set the background an id. Once you did that then you should be able to use the following to set the background image using that id.

To set the id for the layout, just use android:id="@+id/yourBackgroundViewIDHere" in your layout, as follows:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/yourBackgroundViewIDHere"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<!-- Your layout stuff here -->

</RelativeLayout>

This is for a RelativeLayout (substitute your layout type if you're not using a RelativeLayout) and you could call it from onCreate():

RelativeLayout yourBackgroundView = (RelativeLayout) findViewById(R.id.yourBackgroundViewIDHere);

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
        yourBackgroundView.setBackgroundDrawable(d);
    } else {
        yourBackgroundView.setBackground(d);
    }