Passing a string variable from one activity to another is easy peasy. We use putExtra & getExtra methods of Intent class as follows.
Intent i = new Intent(this, SecondActivity.class); i.putExtra("KEY",YourData);To get the string value back in SecondActivity class,we use code
Bundle extras = getIntent().getExtras(); if(extras !=null) { String value = extras.getString("KEY"); }What about passing object from one activity to another?
In this sample project, we want to pass an instance of an ToDoItem from our main activity to another.
ToDoItem will hold these information: Title, Priority,status,date & time.
First, we construct the ToDoItem like any Java Object.
Create all the fields you want the object to contain and generate
getters and setters for each. We then create the methods we would need to be
able to pass, and subsequently receive, this object between activities.
To pass an ToDoItem, we would need to put it in an Intent
and pass it using
Intent.putExtra(String key, Bundle bundle).
public static void packageIntent(Intent intent, String title, Priority priority, Status status, String date) { intent.putExtra(ToDoItem.TITLE, title); intent.putExtra(ToDoItem.PRIORITY, priority.toString()); intent.putExtra(ToDoItem.STATUS, status.toString()); intent.putExtra(ToDoItem.DATE, date); }
Here, we simply put all the values in the object that we
want to pass
Next, we should be able to convert this back to an ToDoItem
object in the receiving Activity. This
task is done by the following method:
ToDoItem(Intent intent) { mTitle = intent.getStringExtra(ToDoItem.TITLE); mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY)); mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS)); try { mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE)); } catch (ParseException e) { mDate = new Date(); } }
I created a simple app that asks the user for the five
values we would need to populate ToDoItem.
When the user clicks on the "create item" button,
the application creates a new ToItemItem based on the values in
the form and adds this to an ArrayList of ToDoItems.
private void onCreateToDoItem() { // Create a newToDoItem ToDoItem todoitem = new ToDoItem (); todoitem. setTitle (mTitleText.getText().ToString()); todoitem. setPriority(getPriority) todoitem. setStatus(getStatus) todoitem. setDate(getDate) // You can then do whatever you want with this object // like adding it to an ArrayList or saving it to a database mItems.add(todoitem); Toast.makeText(ObjectSender.this, "ToDoItem added!", Toast.LENGTH_SHORT).show(); }When the user clicks on the "submit item" button,
private void onSubmitObject() { Intent intent = new Intent(ObjectSender.this, ObjectReceiver.class); // For simplicity, we will always get the second value // In a "real" application, the Key should be defined in a constants file Intent data = new Intent(ObjectSender.this,ObjectReceiver.class); ToDoItem.packageIntent(data, titleString, priority, status, fullDate); //TODO - return data Intent and finish startActivity(data); }Upon receiving the Intent, the new activity simply displays the values in the ToDoItem passed into it. Here's how we can get back the value.
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_item); // Get the extras passed to this Activity setUpViews(getIntent().getExtras()); } private void setUpViews(Bundle extras) { ToDoItem toDoItem = new ToDoItem(getIntent()); // The ToDoItem fields are now populated, so we set the texts ((TextView) findViewById(R.id.titleView)).setText(toDoItem.getTitle()); ((TextView) findViewById(R.id.priorityView)).setText(toDoItem.getPriority().toString()); ((TextView) findViewById(R.id.StatusLabel)).setText(toDoItem.getStatus().toString()); ((TextView) findViewById(R.id.dateView)).setText(toDoItem.FORMAT.format(toDoItem.getDate())); }Here's how the sending & receiving screen activity looks like.
Here is the ToDoItem class
package com.example.passobject; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.content.Intent; public class ToDoItem { public static final String ITEM_SEP = System.getProperty("line.separator"); public enum Priority { LOW, MED, HIGH }; public enum Status { NOTDONE, DONE }; public final static String TITLE = "title"; public final static String PRIORITY = "priority"; public final static String STATUS = "status"; public final static String DATE = "date"; public final static String FILENAME = "filename"; public final static SimpleDateFormat FORMAT = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US); private String mTitle = new String(); private Priority mPriority = Priority.LOW; private Status mStatus = Status.NOTDONE; private Date mDate = new Date(); ToDoItem(String title, Priority priority, Status status, Date date) { this.mTitle = title; this.mPriority = priority; this.mStatus = status; this.mDate = date; } // Create a new ToDoItem from data packaged in an Intent ToDoItem(Intent intent) { mTitle = intent.getStringExtra(ToDoItem.TITLE); mPriority = Priority.valueOf(intent.getStringExtra(ToDoItem.PRIORITY)); mStatus = Status.valueOf(intent.getStringExtra(ToDoItem.STATUS)); try { mDate = ToDoItem.FORMAT.parse(intent.getStringExtra(ToDoItem.DATE)); } catch (ParseException e) { mDate = new Date(); } } public ToDoItem(){ } public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public Priority getPriority() { return mPriority; } public void setPriority(Priority priority) { mPriority = priority; } public Status getStatus() { return mStatus; } public void setStatus(Status status) { mStatus = status; } public Date getDate() { return mDate; } public void setDate(Date date) { mDate = date; } // Take a set of String data values and // package them for transport in an Intent public static void packageIntent(Intent intent, String title, Priority priority, Status status, String date) { intent.putExtra(ToDoItem.TITLE, title); intent.putExtra(ToDoItem.PRIORITY, priority.toString()); intent.putExtra(ToDoItem.STATUS, status.toString()); intent.putExtra(ToDoItem.DATE, date); } public String toString() { return mTitle + ITEM_SEP + mPriority + ITEM_SEP + mStatus + ITEM_SEP + FORMAT.format(mDate); } public String toLog() { return "Title:" + mTitle + ITEM_SEP + "Priority:" + mPriority + ITEM_SEP + "Status:" + mStatus + ITEM_SEP + "Date:" + FORMAT.format(mDate); } }Here is the main activity which sends the object
package com.example.passobject; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Date; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.example.passobject.ToDoItem.Priority; import com.example.passobject.ToDoItem.Status; import com.example.passobject.ToDoItem; public class ObjectSender extends Activity { // 7 days in milliseconds - 7 * 24 * 60 * 60 * 1000 private static final int SEVEN_DAYS = 604800000; private static String timeString; private static String dateString; private static TextView dateView; private static TextView timeView; private final ListHere is script for activity which receives it.mItems = new ArrayList (); private Date mDate; private RadioGroup mPriorityRadioGroup; private RadioGroup mStatusRadioGroup; private EditText mTitleText; private RadioButton mDefaultStatusButton; private RadioButton mDefaultPriorityButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_todo); mTitleText = (EditText) findViewById(R.id.title); mDefaultStatusButton = (RadioButton) findViewById(R.id.statusDone); mDefaultPriorityButton = (RadioButton) findViewById(R.id.medPriority); mPriorityRadioGroup = (RadioGroup) findViewById(R.id.priorityGroup); mStatusRadioGroup = (RadioGroup) findViewById(R.id.statusGroup); dateView = (TextView) findViewById(R.id.date); timeView = (TextView) findViewById(R.id.time); // Set the default date and time setDefaultDateTime(); // OnClickListener for the Date button, calls showDatePickerDialog() to show // the Date dialog final Button datePickerButton = (Button) findViewById(R.id.date_picker_button); datePickerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showDatePickerDialog(); } }); // OnClickListener for the Time button, calls showTimePickerDialog() to show // the Time Dialog final Button timePickerButton = (Button) findViewById(R.id.time_picker_button); timePickerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showTimePickerDialog(); } }); // OnClickListener for the Cancel Button, final Button cancelButton = (Button) findViewById(R.id.cancelButton); cancelButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { log("Entered cancelButton.OnClickListener.onClick()"); ToDoItem toDoItem = new ToDoItem(); toDoItem. setTitle (mTitleText.getText().toString()); toDoItem. setPriority(getPriority()) ; toDoItem. setStatus(getStatus()); toDoItem. setDate(mDate); // You can then do whatever you want with this object // like adding it to an ArrayList or saving it to a database mItems.add(toDoItem); Toast.makeText(ObjectSender.this, "ToDoItem added!", Toast.LENGTH_SHORT).show(); } }); //OnClickListener for the Reset Button final Button resetButton = (Button) findViewById(R.id.resetButton); resetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { log("Entered resetButton.OnClickListener.onClick()"); mTitleText.setText(""); mDefaultStatusButton.setChecked(true); mDefaultPriorityButton.setChecked(true); setDefaultDateTime(); } }); // OnClickListener for the Submit Button // Implement onClick(). final Button submitButton = (Button) findViewById(R.id.submitButton); submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { log("Entered submitButton.OnClickListener.onClick()"); // Gather ToDoItem data Priority priority = getPriority(); Status status = getStatus(); String titleString = mTitleText.getText().toString(); // Date String fullDate = dateString + " " + timeString; // Package ToDoItem data into an Intent Intent data = new Intent(ObjectSender.this,ObjectReceiver.class); ToDoItem.packageIntent(data, titleString, priority, status, fullDate); startActivity(data); } }); } // Use this method to set the default date and time private void setDefaultDateTime() { // Default is current time + 7 days mDate = new Date(); mDate = new Date(mDate.getTime() + SEVEN_DAYS); Calendar c = Calendar.getInstance(); c.setTime(mDate); setDateString(c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)); dateView.setText(dateString); setTimeString(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.MILLISECOND)); timeView.setText(timeString); } private static void setDateString(int year, int monthOfYear, int dayOfMonth) { // Increment monthOfYear for Calendar/Date -> Time Format setting monthOfYear++; String mon = "" + monthOfYear; String day = "" + dayOfMonth; if (monthOfYear < 10) mon = "0" + monthOfYear; if (dayOfMonth < 10) day = "0" + dayOfMonth; dateString = year + "-" + mon + "-" + day; } private static void setTimeString(int hourOfDay, int minute, int mili) { String hour = "" + hourOfDay; String min = "" + minute; if (hourOfDay < 10) hour = "0" + hourOfDay; if (minute < 10) min = "0" + minute; timeString = hour + ":" + min + ":00"; } private Priority getPriority() { switch (mPriorityRadioGroup.getCheckedRadioButtonId()) { case R.id.lowPriority: { return Priority.LOW; } case R.id.highPriority: { return Priority.HIGH; } default: { return Priority.MED; } } } private Status getStatus() { switch (mStatusRadioGroup.getCheckedRadioButtonId()) { case R.id.statusDone: { return Status.DONE; } default: { return Status.NOTDONE; } } } // DialogFragment used to pick a ToDoItem deadline date public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { setDateString(year, monthOfYear, dayOfMonth); dateView.setText(dateString); } } // DialogFragment used to pick a ToDoItem deadline time public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current time as the default values for the picker final Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR_OF_DAY); int minute = c.get(Calendar.MINUTE); // Create a new instance of TimePickerDialog and return return new TimePickerDialog(getActivity(), this, hour, minute, true); } public void onTimeSet(TimePicker view, int hourOfDay, int minute) { setTimeString(hourOfDay, minute, 0); timeView.setText(timeString); } } private void showDatePickerDialog() { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getFragmentManager(), "datePicker"); } private void showTimePickerDialog() { DialogFragment newFragment = new TimePickerFragment(); newFragment.show(getFragmentManager(), "timePicker"); } private void log(String msg) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Log.i(TAG, msg); } }
package com.example.passobject; import com.example.passobject.ToDoItem; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; public class ObjectReceiver extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.todo_item); // Get the extras passed to this Activity setUpViews(getIntent().getExtras()); } private void setUpViews(Bundle extras) { ToDoItem toDoItem = new ToDoItem(getIntent()); // The AttendeeObject fields are now populated, so we set the texts ((TextView) findViewById(R.id.titleView)).setText(toDoItem.getTitle()); ((TextView) findViewById(R.id.priorityView)).setText(toDoItem.getPriority().toString()); ((TextView) findViewById(R.id.StatusLabel)).setText(toDoItem.getStatus().toString()); ((TextView) findViewById(R.id.dateView)).setText(toDoItem.FORMAT.format(toDoItem.getDate())); } }
It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in android programming your post help me a lot.Thanks for your informative article. Best Android Training in chennai
ReplyDeleteThank You! For sharing such a great article, It's been a amazing article.
ReplyDeleteIt's provide lot's of information, I really enjoyed to read this.
I hope, i will get these kinds of information on a regular basis from your side.
I follows your site, and share your's content because it is so much useful.
Source: Play Sports Free
Keyword: Way to Earn Money
Read: Wrestle Mania 36
Watch: Wrestling Video