I am a beginner in both Java and Android, and I think this is more of a Java question as it manifests in Android.
I am using an Android support package (android.support.v4.app) and creating a dialog using DialogFragment in my base class called MyActivity, which extends FragmentActivity.
The question I have concerns calling a function in the MyActivity class from an OnClick method in an OnClickListener method for a button in the DialogFragment.
It is working; I just want to understand why.
If I try to reference the function directly (MyActivity.someFunction()) I get “Cannot make a static reference to the non-static method someFunction() from the type MyActivity.” Anybody have a good way to explain static vs. non-static and why this particular reference is static? I assume it’s because the DialogFragment is declared as static. What is the purpose of declaring a subclass/method static vs. non-static. That is, why does it matter if the method belongs to the class and not the instantiated object?
Also, why and how does the casting get around the static reference in this example?
Thanks!
public static class myDialogFragment extends DialogFragment {
static myDialogFragment newInstance(int whichDialog) {
myDialogFragment f = new myDialogFragment();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.invasive_edit_dialog, container, true);
Button btn_apply_coords = (Button)v.findViewById(R.id.btn_get_coord);
btn_apply_coords.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// This does not work ("Cannot make a static reference to the non-static method someFunction() from the type MyActivity").
MyActivity.someFunction();
// This does not work ("The method someFunction() is undefined for the type FragmentActivity"). Eclipse suggests casting (a few lines down).
getActivity().someFunction();
// This works; casted version of code above. What is this code doing?
((MyActivity) getActivity()).someFunction();
// this works also
MyActivity thisActivity = (MyActivity) getActivity();
thisActivity.someFunction();
}
});
return v;
}
}
public void someFunction() {
// do something
}
this didn’t work because you tried to call this method from class(
MyActivity), not from object of that class (e.g. (MyActivity activity))and this did work, because, as I suppose, method
getActivity()returned object, that was casted toMyActivity, and then non-static method fromMyActivitywas invoked on that objectTo sum up – you can’t call non-static methods without having object that you can call them on.