Reputation: 3733
I had this problem
Launching a new activity - android
and don't understand why the original code was wrong. Also, even more confusing later on in the activity i have the following code which works using getActivity() what is the difference why does it work in one case and not the other?
public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
EditText dobText = (EditText)getActivity().findViewById(R.id.editText1);
String dobStr = dobText.getText().toString();
int day = Integer.valueOf(dobStr.replaceAll("([0-9]*)/[0-9]+/[0-9]+","$1"));
int month = Integer.valueOf(dobStr.replaceAll("[0-9]+/([0-9]+)/[0-9]+", "$1"))-1;
int year = Integer.valueOf(dobStr.replaceAll("[0-9]+/[0-9]+/([0-9]+)", "$1"));
return new DatePickerDialog(getActivity(),this, year,month,day);
}
}
and how is my case in the previous question different to this one
http://developer.android.com/guide/components/fragments.html
(search for "intent.setClass(getActivity(), DetailsActivity.class);" to find the example I'm referring to)
Upvotes: 0
Views: 4207
Reputation: 423
In this example you are extending DialogFragment, this does not extend from Activity but Fragment.
Here you are calling the getActivity() method of Fragment which returns the attached Activity object for the Fragment.
In the previous question the class was extending Activity, so 'this' is a reference to an Activity.
The complication arises because in the previous question you were accessing 'this' from an anonymous inner class, which dosen't extend from Activity so to access the enclosing object you have to specify the name of the enclosing class i.e MainActivity.this.
Here's the Oracle tutorial on inner classes, the syntax can be confusing at first.
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
Upvotes: 1