Posts tagged Intent
Take Photo Using ACTION_IMAGE_CAPTURE Intent
3In this post we will build a working sample app that allows the user to press a button to take a photo using the phone’s camera app (or any other available) and then loads this photo into an ImageView. You could of course do anything you like with the photo such as upload it to a web service or save it to permanent storage.
Begin by creating a new Android project, then open up your main.xml layout file and edit it. The below xml creates an ImageButton and an ImageView. Everything we need for the sample. The ImageView references a placeholder image.. just a little snap of someone I spotted the last time I was at the beach.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:background="#FFFFFF">
<ImageButton
android:id="@+id/btn_take_photo"
android:src="@android:drawable/ic_menu_camera"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp" />
<ImageView
android:id="@+id/img_main"
android:src="@drawable/kiss_from_a_rose"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:scaleType="fitXY"
android:adjustViewBounds="true"
android:padding="5dp" />
</LinearLayout>
In your Activity’s onCreate() method, attach a listener to the button. When the button is clicked we want to start an ACTION_IMAGE_CAPTURE Intent using startActivityForResult().
findViewById(R.id.btn_take_photo).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, REQ_CODE_PHOTO_TAKE);
}
});
You’ll also need to create the REQ_CODE_PHOTO_TAKE constant. This value will be returned in the resultCode.
private static final int REQ_CODE_PHOTO_TAKE = 1;
Next up push Alt+Shift+S and click “Override/Implement Methods” from the menu. Choose to Override onActivityResult() and click ok.
You’ll notice this method has three parameters. ‘resultCode’ is self explanatory – if this is anything other than RESULT_OK we’ll want to return immediately. An example where this might happen is if the user were to push the button to take a photo but then push their phone’s back button immediately rather than take one. requestCode contains the value that we passed in during startActivityForResult(), in our case this is REQ_CODE_PHOTO_TAKE. Lastly is the returned Intent. We can use this to get a Uri to the data by calling getData().
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode != RESULT_OK) return;
switch (requestCode) {
case REQ_CODE_PHOTO_TAKE:
Uri u = data.getData();
onPhotoReturned(u);
break;
default:
break;
}
}
Lastly we’ll want to display the photo in our ImageView. Create the new method, onPhotoReturn(Uri u). We use the Uri to open an InputStream and from this we can create a BitmapDrawable which can be used to set the Drawable for the ImageView.
private void onPhotoReturned(Uri u) {
InputStream is = null;
try {
ContentResolver cResolver = getContentResolver();
is = cResolver.openInputStream(u);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
BitmapDrawable bmp = new BitmapDrawable(is);
ImageView mainImage = (ImageView)findViewById(R.id.img_main);
mainImage.setImageDrawable(bmp);
}
Working code for this app can be found on my github and a screenshot of it in action is below:
Android: Send email with pre-populated fields
1Within the AppInfoActivity of my current project, I have a button to send an email to the developer (me!). This button creates an Intent and uses Intent.putExtra to pre-populate the Email, subject and body of the email.
Initially my Email “To” field wasn’t populating – if this is happening to you, it’s probably because it’s expecting a String array (to allow for multiple email addresses) and not a single String object, you’ll notice this is different in the onClick handler below:
public void onEmailButtonClick(View v) {
final Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { getString(R.string.app_email_address) });
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_info_email_subject));
emailIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.app_info_email_body));
startActivity(emailIntent);
}
and for completeness, here’s the xml for the string resources referenced:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_info_email_subject">Feedback on someOldApp</string> <string name="app_info_email_body">Hi someOldApp,</string> <string name="app_email_address">someoldapp@samcoles.co.uk</string> </resources>
Android: Passing data between Activities
5With the Android framework, data can be passed between different Activities by adding it to the Intent object before starting the new Activity, and then retrieving it using a Bundle object. We will demonstrate this by creating a small demo with two Activities, the first activity, TextInputActivity will allow the user to type in some text and tap a button. Tapping the button will open ViewTextActivity, taking the inputted text with it in the Intent, this text will be retrieved and displayed in ViewTextActivity.
This demo will cover the method for primitive data types, we’ll cover passing your own data types/objects in another post.
First we will get the layouts out the way, both are very simple.
text_input_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <EditText android:id="@+id/the_input" android:layout_width="250dp" android:layout_height="wrap_content" android:layout_weight="1"/> <Button android:id="@+id/the_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to next Activity" android:onClick="goToNextActivity"/> </LinearLayout>
text_view_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/the_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10pt"/> </LinearLayout>
Now we’ll create TextInputActivity, this is declared as the main activity in the AndroidManifest.xml. In here we’ll add the onClick handler, goToNextActivity() that’s referenced in the xml layout. Within this method, first we’ll get a reference to the EditText and extract the text from it to a String. Then we create a new Intent object to ViewTextActivity. We’ll call Intent.putExtra() to add the String to the Intent. the first parameter is the name we’ll use to retrieve it later – this is a constant that we’ll declare in ViewTextActivity so don’t worry about the error for now. We’ll just need to remember to add this constant and give it public access in TextViewActivity. Finally, call startActivity() passing it our Intent to start the new Activity.
TextInputActivity.java
package samcoles.bundleexample;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class TextInputActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_input_layout);
}
public void goToNextActivity(View v) {
String theText = null;
//first get the EditText View and extract the text...
EditText theInput = (EditText)findViewById(R.id.the_input);
if(theInput != null) {
theText = theInput.getText().toString();
}
//create a new Intent
Intent i = new Intent(this, ViewTextActivity.class);
//add theText to the intent
i.putExtra(ViewTextActivity.TEXT_DATA, theText);
//start the activity
startActivity(i);
}
}
Next we’ll add our second Activity, ViewTextActivity. Remember to add this to your AndroidManifest.xml or your app will crash!
First we’ll define the public constant TEXT_DATA that we used in TextInputActivity.
public static final String TEXT_DATA = "textData";
Then in the overridden onCreate() method we’ll get a reference to the Bundle object in the Intent by calling getIntent().getExtras(). We’ll then call Bundle.getString(), passing the TEXT_DATA constant to retrieve our value. Finally we’ll get a reference to the TextView in our layout and call TextView.setText() passing our String.
ViewTextActivity.java
package samcoles.bundleexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class ViewTextActivity extends Activity {
public static final String TEXT_DATA = "textData";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text_view_layout);
Bundle extras = getIntent().getExtras();
if(extras != null) {
String theText = extras.getString(TEXT_DATA);
if(theText != null) {
TextView t = (TextView)findViewById(R.id.the_text);
if(t != null) {
t.setText(theText);
}
}
}
}
}
Here’s a screenshot of each activity in the demo in action:

