Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The way you're attempting to do it is not possible, I'm afraid. One of the things you'll want to learn as a new Android developer is how the cycle between activities works. In your case, you're running an <code>Activity</code> that calls upon an <code>Intent</code> to get data from it. However, in the Android API, an <code>Intent</code> can only be referenced on its own time. This means you can't use your <code>getImage()</code> method the way you had tried.</p> <p>There is hope, though!</p> <p>What you first need to do is call the <code>Intent</code>. You will do this through the code you have now in <code>getImage()</code>:</p> <pre><code>public void getImage() { // This has to be a void! Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 10); } </code></pre> <p>This method will now start the Image Picker that you want users to select from. Next, you have to catch what is returned. This <strong>cannot</strong> be returned from your <code>getImage()</code> method, but instead must be collected from elsewhere.</p> <p>You must implement the below method:</p> <pre><code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { final int SELECT_PICTURE = 1; // Hardcoded from API if (requestCode == SELECT_PICTURE) { String pathToImage = data.getData().getPath(); // Get path to image, returned by the image picker Intent mDrawableBg = Drawable.createFromPath(pathToImage); // Get a Drawable from the path } } } </code></pre> <p>Lastly, instead of calling <code>mDrawableBg = getResources().getDrawable(getImage());</code>, just call <code>getImage();</code>. This will initialize the Image Picker.</p> <p>Some reading:</p> <ul> <li><a href="http://developer.android.com/reference/android/app/Activity.html" rel="nofollow noreferrer">Android <code>Activity</code> (notably stuff about <code>Intent</code>s and getting a result back)</a></li> <li><a href="http://developer.android.com/reference/android/graphics/drawable/Drawable.html" rel="nofollow noreferrer">Android <code>Drawable</code></a></li> <li><a href="https://stackoverflow.com/questions/5834221/android-drawable-from-file-path">Getting a <code>Drawable</code> from a path</a></li> <li><a href="https://stackoverflow.com/questions/2507898/how-to-pick-a-image-from-gallery-sd-card-for-my-app-in-android">More on the Image Picker <code>Intent</code></a></li> </ul> <p>Good luck!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload