Categories
Android

Sending data to other activities in Android

Let’s say you have a list activity which lists some information and you have another activity which adds/edits information in the list. How do you tell the edit activity which item (in the list of the first activity) needs to be edited? 

 

In the first activity, you will do this :

/*********************************************
* These constants will be passed to the second activity and
* the second activity will return this back when it returns its
* result
**********************************************/
private static final int ALERT_ADD = 100;
private static final int ALERT_EDIT = 110;

public void callAddEditActivity() {
	// get the unique ID of the selected
	long itemId = this.getListView().getSelectedItemId();

	/** If no item was selected, then this condition will be true */
	if (itemId == ListView.INVALID_ROW_ID) {
		//put an alert here asking to select something
		return;
	}
	/**************************************************
	* Now, we will get the position of the item in the list. From that
	* we can get the cursor object, which will contain other information
	* about it. In this case, I want to get the name  and phone number.
	*
	* The cursor object is a regular cursor you use with a database.
	* Refer to my post about using databases with Android for more
	* information on it.
	***************************************************/
	int pos  = this.getListView().getSelectedItemPosition();
	Cursor c = (Cursor) this.getListView().getAdapter().getItem(pos);
	
	/***************************************************
	* Now, you can create a "bundle" which can be passed to setCotntact.
	* SetContact is the other activity which is used for adding/editing
	* names and phone numbers. It will use the bundle to get the data
	* for the item it is supposed to edit.
	****************************************************/

	Intent in1  = new Intent();
	Bundle bun = new Bundle();
	
	bun.putLong("id", c.getLong(3));
	bun.putString("name", c.getString(0));
	bun.putString("phone", c.getString(1));
	in1.setClass(this, SetContact.class);
	in1.putExtras(bun);
	
	startActivityForResult(in1, ALERT_EDIT);
}

Let’s take a look at SetContact activity which be used to edit (or add) data to the list.

package gContact.gContact;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;

public class SetContact extends Activity {
	private EditText txtName;
	private EditText txtPhone;
	private long id;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		/** This piece is not important */
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_contact);
		txtName = (EditText) findViewById(R.id.alertText);
		txtPhone = (DatePicker) findViewById(R.id.alertDate);

		/********************************************
		* When data is passed to any activity in a bundle, it can be
		* accessed through getExtras(). If nothing is passed, then this
		* bundle will be null.
		*
		* If the bundle is null, then that means we are adding a new item
		* otherwise we are editing an existing item
		*********************************************/
		Bundle bun = getIntent().getExtras();
		if (null == bun) return;

		/*********************************************
		* If this is an edit, then set the proper values in the text boxes
		**********************************************/
		this.id     = bun.getLong("id");
		String text = bun.getString("name");
		String phone = bun.getString("phone");

		if (null != text) txtName.setText(text);
		if (null != phone) txtPhone.setText(phone);
	}

	/*****************************************
	* This creates a menu with 2 buttons  - save and cancel
	******************************************/
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuItem item1 = menu.add(0, 0, 0,"Save");
		MenuItem item2 = menu.add(0, 1, 1, "Cancel");
		return true;
	}

	/*********************************************
	* This function is run when one of our menu items is selected.
	**********************************************/
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		/**************************************
		*  If Save was clicked/pressed/tapped then we
		* gather name and phone number and pass it to the
		* main activity so it can add it to the database.
		*
		* Adding to the database can be done here too, but
		* I like doing it in the main activity
		***************************************/
		case 0:
			Bundle conData = new Bundle();
			String name = txtName.getText().toString();
			String phone = txtPhone.getText().toString();

			conData.putString("name", name);
			conData.putString("phone", phone);
			conData.putLong("id", this.id);

			Intent mIntent = new Intent();
			mIntent.putExtras(alertData);
			setResult(RESULT_OK, mIntent);
			break;

		case 1: // Cancel
			break;
		}
		finish();
		return true;
	}
}

When the second activity sends data back to the first activity, onActivityResult method is called (in the first activity). It will look something like this :

protected void onActivityResult(int requestCode, int resultCode, Intent data){
	switch (requestCode) {
	case ALERT_ADD:
		if (resultCode != RESULT_CANCELED) {
			Bundle res = data.getExtras();

			/***********************************************
			* After we get the new information from the second activity, we
			* can add it to the database and then refresh the list. If the below
			* statement is unclear, refer to my blog post on databases and
			* Android
			************************************************/
			db.createContact(
				res.getString("name"),
				res.getString("phone")
			);
			fillData();
		}
		break;

	case ALERT_EDIT:
		if (resultCode != RESULT_CANCELED) {
			Bundle res = data.getExtras();
			db.updateContact(res.getLong("id"), res.getString("name"), res.getString("phone"));
			fillData();
		}
		break;
	}
}