Activity is NULL in fragment, but not always in Android - android

The this.getActivity() is NULL in my fragment, and is called from the actual activity itself. This doesnt always happens but how can I fix this?
sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));
EventActivity.java
eventsFragment.setUpEvents(getEventApplication());
EventsFragment.java
public void setUpEvents(Application application) {
sportButton.setBackgroundColor(ViewHelper.getColor(this.getActivity()));

just remove this from this.getActivity() and if you extends your
Activity from AppCompatActivity then you have to cast it with same
like below
(AppCompatActivity) getActivity()

If its fragment which runs inside a parent activity then in that case you can create a static Activity object in EventActivity and reference that in fragments instead of getActivity(), because its guaranteed to be available to the fragments.
EventActivity.class
protected Activity activity;
onResume()
{
activity = this;
}
EventsFragment.class
sportButton.setBackgroundColor(ViewHelper.getColor(EventActivity.activity));
hope it helps

Related

Fragment getActivity() -- avoiding NPE

I have a single Activity application with a number of Fragments (15 or so). Some of the methods in my MyActivity are required by all the Fragments, such as displaying Dialogs. So what I have in a sample call from a Fragment (and they all extend MyFragment) is something like:
getMyActivity().displayDialog(msg);
and getMyActivity is defined as in MyFragment:
MyActivity getMyActivity() {
return (MyActivity) getActivity();
}
however, sometimes getActivity() is null so I get NPEs in that case. So what I'm doing is moving those methods into MyFragment such that:
protected void displayDialog(String msg) {
if (getMyActivity() != null) {
getMyActivity().displayDialog(msg);
} else {
// what do I do here?
}
}
Does this approach make sense for the 10 or so methods I need to reference from MyActivity (and are there any pitfalls to doing so)? Also, what would I do to provide feedback in the case where getActivity() is null?
Edit: A common example of a cause for a NullPointerException would be something like a network call being dispatched by the Fragment and on completion of said network call, trying to display a Dialog when the Activity was destroyed in the meantime.
Its better to use some ParentFragment for example
public abstract class ParentFragment extends Fragment {
public Activity activity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = activity;
}
}
then you must owerride all yor fragments
public class SomeFragment extends ParentFragment {}
and use there activity for
activity.displayDialog(msg);
If the return value of getActivity () == null, then the Fragment is not attached in the FragmentManager of your parent activity.
A common mistake is to hold references of those fragments as object variables in the parent activity. This results in NPEs from Fragments.
I would recomend you to check whether this is your case.
If not, then:
See whether you are removing the Fragments from FragmentManager correctly
See whether you are adding the Fragments to the Framgnetmanager the right way.
if yes, remove the object variables and add the Fragments through the FragmentManager, see: http://www.survivingwithandroid.com/2013/04/android-fragment-transaction.html
Hope this helps

What callback exists for a FragmentActivity, ie. onAllFragmentsHaveBeenCreated()?

I am trying to find a callback for my FragmentActivity that happens 'after' all of the fragments have called 'onCreateView'.
The reason for this is that my Fragment implement my interface:
public interface LifeCycleFragment {
public void onResumeFragment();
}
and when i call the fragment from MyActivity:
class MyActivity extends Activity
onCreate()
fragment.onResumeFragment()
getActivity() ends up being null:
class MyFragment extends Fragment implements LifeCycleFragment
#Override
public void onResumeFragment() {
Log.e(TAG, "- ON RESUME -");
FragmentActivity activity = getActivity();
// *****ACTIVITY IS NULL HERE AND THAT'S A PROBLEM ***//
I am not sure how to tackle this problem and any help would be appreciated.
Place getActivity() in override onActivityCreated method, and save it in the class for onResumeFragment(). I hope the Activity is still kept the same during onPause().
Would you like sample code to communicate between Fragment and Activity? I posted an answer in SO about it # Passing data between fragments contained in an activity. The respective Google webpage is # Communicating with Other Fragments.
Good luck and have fun...

Calling Activity Method From Inside A Fragment [duplicate]

This question already has answers here:
Call an activity method from a fragment
(18 answers)
Closed 9 years ago.
I am trying to call a method in an activty from a Fragment screen.
I have a method called myMethod() which is in an activity called MyActivity;
I have a fragment called Screen1Fragment.
I would like to call MyActivity.myMethod() from inside the Screen1Fragment but I am not sure how to do this.
Previously the Screen1Fragment was an activity and so I was extending MyActivity so that I could directly call
myMethod().
But I have had to change the activity to a fragment for sliding tabs usage.
Thanks in advance.
Use getActivity() in your fragment.
MyActivity activity = (MyActivity) getActivity();
activity.myMethod();
if you are not sure if your fragment is attached to MyActivity then
Activity activity = getActivity();
if(activity instanceof MyActivity){
MyActivity myactivity = (MyActivity) activity;
myactivity.myMethod();
}
You should make your fragment totally independant of the activity you are attaching it to. The point of Fragments is that you can re-use them in different contexts with different activities. To achieve that and still being able to call methods from your Activity the following pattern in recommended in the official documentation.
In your fragment:
define a public interface with the method
public interface MyFragmentCallback{
public void theMethod();
}
define a field and get a cast reference:
private MyFragmentCallback callback;
public void onAttach(Activity activity){
callback = (MyFragmentCallback) activity
super.onAttach(activity);
}
In your Activity
implement MyFragmentCallback in the class definition.
implement theMethod() in your activity (Eclipse will ask you to do so)
Then, from your fragment, you can call callBack.theMethod()
The difference between this and simply calling your method on getActivity() is that your fragment is not paired with this specific activity anymore. So you may re-use it with other activity for example one for phones and the other for tablets.
If the method is the static method of MainActivity, something like:
public static void someMethod(){}
Then, it is pretty straightforward. Just call
MainActivity.someMethod()
However, I guess what you really want is to access some function from the Activity class. Then you can use the following code in the Fragment view creater
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
container.getContext().someMethod();
}

Android: NullPointerException in dialog when rotating

Sorry if this been asked before but I couldn't find an answer to my specific case. Also sorry that I'm new and a little stupid.
Problem:
I'm showing a dialog from a fragment and passing along a context in my constructor method because I need a context in my dialog to register for broadcastrecievers etc.
DialogFragment fragmentDialog = MyDialog.myConstructor(getActivity());
fragmentDialog.show(getFragmentManager(), "dialog");
Then in MyDialog class I store the context in a instance variable.
The problem arises when rotating the device and I get a nullPointerException when I try to use the context again in the dialog.
Can this be solved in some easy way?
If the device is rotated the Activity will be destroyed and recreated. So the Context you passed to your Fragment points on the Activity which was destroyed.
You could use setRetainInstance(true) in your Fragment. This way your Fragment will survive the recreation of the Activity.
To solve the NPE you have to pass the Context to the Fragment, if the Activity is recreated. Then the Context belongs to the new Activity.
In fact, without this update every line of code which points on the Activity like getActivity() or getFragmentManager() will lead in a NPE.
You get the NullPointerException because activites are destroyed and recreated when rotating the screen.
The SO post below gives more info...
https://stackoverflow.com/a/1673374/
Please be careful with the order of events if you rotate a FragmentActivity, because this can also be a source of NullPointerExceptions.
This is not documentated:
When the FragmentActivity is created the first time,
public class MyActivity extends FragmentActivity implements
MyFragment.OnFragmentInteractionListener {
private int var1;
private int var2;
#Override
protected void onCreate(Bundle savedInstanceState) {
//before
var1 = 3;
super.onCreate(Bundle savedInstanceState)
//after
var2 = 5;
}
//Interface Methods
public int getVar1() { return var1; }
public int getVar2() { return var2; }
}
both of the [before] and [after] code will be run before the fragments are attached and created. So, if you get the vars in the onCreate() call of the Fragment you get both vars. But when you rotate your device, the Activity is recreated from the savedInstanceState in the super call. Now, the fragments are reattached and created anew in this call! That means, this time the Methods of the Listener Interface are called before your [after] code. So, if you pass the Context of the activity to the fragment and get Information through the Interface like it is shown in: https://developer.android.com/training/basics/fragments/communicating.html
you get a NullPointerException for var2 because the interface methods are called from the fragments onCreate() onAttach() ... functions before the [after] code in the Activity's onCreate() is executed! So, take care that you set your Information the InterfaceFunctions are accessing before the super call.
Depending on what you're doing in your initialization you could consider creating a new class that extends Application and moving your initialization code into an overwridden onCreate method within that class.
public class MyApplicationClass extends Application {
#Override
public void onCreate() {
super.onCreate();
// TODO Put your application initialization code here.
}
}
And you are not stupid, even experts need help from time to time.

Save Activity instance in a Fragment

Fragment has a method named getActivity() which returns the activity with which the fragment currently is associated.
Is it safe to not use this method, but instead save the Activity instance in the onAttach(Activity) method?
For example, change from:
public class MyFragment extends Fragment {
public void foo() {
((MainActivity) getActivity()).foo();
}
}
to:
public class MyFragment extends Fragment {
private MainActivity activity;
public void onAttach(Activity activity) {
this.activity = (MainActivity) activity;
}
public void foo() {
this.activity.foo();
}
}
Are there any differences between these two approaches? Which is better?
PS. One benefit of the second approach is that you don't have to do type conversion each time you use the activity (like (MainActivity) getActivity()). But I don't know whether it's safe to save the activity instance.
yes it's ok. I do that almost always to avoid calling method getActivity() and casting result every time (for better performance and better code)

Categories

Resources