0

Ok, so I have looked through various answers on this site and in practice they all seem great and pretty much the standard way of doing this. Well, standard has failed me. So, I want to have an ImageButton access the gallery and have the user select an image. After the user selects that image I want it to become the ImageButton's background. My code so far is:

package ion.takedown;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;

public class newWrestler extends Activity {
    private String selectedImagePath;
    private ImageButton wrestlerPicture;
    @Override
    protected void onCreate(Bundle newWrestler) {
        super.onCreate(newWrestler);
        setContentView(R.layout.new_wrestler);
        wrestlerPicture = (ImageButton) findViewById(R.id.wrestlerPhoto); 
        wrestlerPicture.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), 1);
            }


        });

    }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                Uri selectedImageUri = data.getData();
                selectedImagePath = getPath(selectedImageUri);
                System.out.println("Image Path : " + selectedImagePath);
                wrestlerPicture.setImageURI(selectedImageUri);
            }
        }
    }
     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 boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}

Please help me It is really getting on my nerves now haha...

Ian Butler
  • 15
  • 3

2 Answers2

0

Use this code.

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
    case 1:
     {
      if (resultCode == RESULT_OK)
      {
       if(requestCode == 1)
        {
         Uri photoUri = data.getData();
         if (photoUri != null)
         {
          try {
              String[] filePathColumn = {MediaStore.Images.Media.DATA};
              Cursor cursor = getContentResolver().query(photoUri, filePathColumn, null, null, null); 
              cursor.moveToFirst();
              int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
              String filePath = cursor.getString(columnIndex);
              cursor.close();
              bMap_image = BitmapFactory.decodeFile(filePath);
              wrestlerPicture.setImageResource.setImageBitmap(bMap_image);


     }catch(Exception e)
      {}
      }
    }
    }
  }
}
Ahmad Raza
  • 2,850
  • 1
  • 21
  • 37
  • If I were choosing from my assets this would be more applicable but, I am having the user choose from their own gallery and not my resources. Sorry if I was not more clear up top with my question, thanks though. – Ian Butler Jul 30 '13 at 04:15
  • 1
    I have updated my answer, Use this code. Hope this will helpful. Thanks – Ahmad Raza Jul 30 '13 at 04:30
0

(1) Don't say "It is really getting on my nerves" and then "haha..." It makes me think you've got a plastered smile on your face, and a knife behind your back.

(2) cursor.moveToFirst() returns a boolean, so:

if(cursor.moveToFirst())
   Log.d("CURSOR STATUS: ", "SUCCESSFULLY MOVED TO FIRST");
else
   Log.d("CURSOR STATUS: ", "FAILED TO MOVE TO FIRST :'(");

(3) What's this printing?

System.out.println("Image Path : " + selectedImagePath);

If it's printing the actual uri path, that helps a LOT. But you should use Logcat, not System.

(4) I do something like this in my own app, but I'm changing an imageview. Maybe the code will be of use:

Uri selectedImageUri = data.getData();
                //In the following code, I'm trying to get 
                //the path for the image file 
                try {
                    imageBMP = null;
                    String selectedImagePath = getPath(selectedImageUri);
                    if (selectedImagePath != null) {
                        filePath = selectedImagePath;
                        //Potentially long-running tasks must be put on their own
                        //thread.
                        Thread DecodeRunnable = new Thread(new Runnable(){
                            public void run() {
                                    decodeFile();
                            }
                        });             
                        DecodeRunnable.start();
                    }
                 }//try

And here's the decodeFile() method:

    public void decodeFile() {
    //This method decodes the file from base 64 to base 32,
    //which allows us to manipulate it as a bitmap in android.

    BitmapFactory.Options o = new BitmapFactory.Options();
        //This option lets us create a bitmap without the extra
        //overhead of allocating new memory for data on its pixels
    o.inJustDecodeBounds = true;

        //If you see this error, then darkness has befallen us.
    if(BitmapFactory.decodeFile(filePath, o) == null){
        Log.d("DECODING: ", "Error! The file is null in the decoding code!");
    }

    BitmapFactory.Options o2 = new BitmapFactory.Options();
        //This option will scale the file. There's no need to get the full-sized
        //image, since it could crash the app if its size exceeds the memory in
        //the heap (It's Java's fault, not mine.)
    o2.inSampleSize = 2;
    imageBMP = BitmapFactory.decodeFile(filePath, o2);

        //The following code will set the image view that the user sees. That
        //has to be run on the ui thread.
    runOnUiThread(new Runnable(){
        public void run(){
            if (imageBMP != null) {
                Bitmap imageViewBMP = null;
                    //Scale the image if necessary so it doesn't fill the entire
                    //app view, which it will do if it's big enough.
                if(imageBMP.getWidth() > 175 && imageBMP.getHeight() > 200){
                    imageViewBMP = Bitmap.createScaledBitmap(imageBMP, 200, 200, 
                            true);
                }
                else{
                    imageViewBMP = imageBMP;
                }
                imageViewIV.setImageBitmap(imageViewBMP);
            }//if(imageBMP != null)
            else{
                Resources res = getResources();
                imageViewIV.setImageDrawable( res.getDrawable(R.drawable.noimage) );
                photoStatusTV.setText(R.string.no_photo_text);
                Toast.makeText(getApplicationContext(), "No image found.", 
                        Toast.LENGTH_LONG).show();
            }
        }
    });

}//decodeFile()

Should work for you. You'd probably be better using asynctasks than the threads I used, but it's easier to read this way.

Shaquil Hansford
  • 383
  • 1
  • 2
  • 9
  • Ok, so after adding your logging suggestions, nothing came up in the log, that led me to believe the code wasn't even being reached, which was the case. I added in a logging else statement where it checks to see if the result code is okay, which it isn't. The interesting part is that its logging that its not okay before I have even finished choosing the picture from the gallery so still a bit stumped. If you have anything that may lend to that, I'd be most appreciative. I'm going to see if I can fix my code if not then I will see what I would be able to do with yours. Thanks. – Ian Butler Jul 30 '13 at 04:12
  • Fixed it and it had nothing to do with the java code, apparently if the activity is defined as single instance in the manifest XML it calls onactivityresult immediately, change it to single top or something else relevant and it works fine. Weird. – Ian Butler Jul 30 '13 at 04:28