Objective
In the day-to-day development, we often use ViewPager+Fragment
to slide the view, in some parts of the logic we may need to take advantage of the context Context
(for example, Basic Toast
), but because Fragment
just attached to the Activity
container of an attempt, if necessary to get the current Activity
context Context
must be getActivity()
obtained by acquiring.
However, I do not know whether the program apes have encountered the occurrence of getactivity () when the null caused the program reported null pointer exception.
The reason can be attributed to the fact that we are:
(a) When switching fragment, will frequently be crash
(ii) Low system memory
(c) At the time of screen switching
....
This can result Activity
in the system being reclaimed, but because fragment
the lifecycle will not be reclaimed as it Actiivty
is reclaimed, the problem of NULL getactivity () is caused.
Solve
Here's a summary of three solutions:
(i) Establishment of a context reference
First we look at Fragment
the life cycle:
In Fragment
the life cycle, the onAttach()
onDetach()
getActivity()
method does not return when the lifecycle is in and between null
. So we can fragment
create a reference at initialization time Context
.
fragment
destroy the reference at the time of destruction.
The code is as follows:
@Override public
void Onattach [activity activity] {
Super.onattach (activity);
Mctx = Activity;//mctx is a member variable, context reference
}
@Override public
void Ondetach () {
super.ondetach ();
Mctx = null;
}
(ii) Rational use of getapplicationcontext ()
Using temporary variables to store context references in Method 1 Context
can solve the problem to some extent. Because in Android,, Application
, Service
Activity
all have context, getapplicationcontext()
can get the global context, so as long as the program does not shut down, get context
very difficult to null
(iii) Customizing your own application
The third method, in fact, is the same as the basic principle of the second method, which is about to be customized application
temporarily to store application
the owning context Context
. In a program, application
get the context by simple access Context
.
The specific use is as follows:
(1) Register your application in the configuration list
<application
android:name= ". MyApplication "
android:icon=" @drawable/ic_launcher "
android:label=" @string/app_name ">
(2) The OnCreate storage context in application and the creation of simple.
public class MyApplication extends application {
private static MyApplication instance;
@Override public
void OnCreate () {
super.oncreate ();
Instance = this;//Store Reference
} public
static MyApplication getinstance () {return
instance;
}
}
Summarize
Here are just a few of the methods I've summed up, and of course there are other developers who have better advice to put forward, and that's better. Everybody together technology share, let everybody progress together!