beginner. Today I wrote a code to jump between activities, using an explicit intent, but I defined an intent member variable in the class, and when I used it in the method, the program crashed. Why is this?
public class MusicPlay extends Activity{
//下面这一句初始化出了错误
public Intent intent=intent=new Intent(this,MusicServer.class);
....
The code is as above, but the error message is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
It is said that an error occurred when calling the getPackageName() virtual method on "null object reference".
At first, I thought that this was empty and caused the problem, so I modified the code:
public class MusicPlay extends Activity{
Intent intent;
public MusicPlay(){
super();
if(this!=null){
intent=new Intent(this,MusicServer.class);
}
}
....
But an error still occurs and the error message is still the same. Through conditional judgment, I know that this is not empty, so why is it still said to be a null reference?
Activity
是ContextWrapper
的子类, 所以我们先找到并打开ContextWrapper.java
Source code, the key code is as follows:ContextWrapper
里基于Context
的调用都是直接使用mBase
来间接实现调用的. 那么这个mBase
是什么时候被赋值的呢? 找到并打开ActivityThread.java
, you can find the code part where it is assigned. The key code is as follows:From the above, it can be seen that: Instantiate any functions and classes related to
Activity
时,ContextWrapper#getBaseContext()
返回的是null, 因此, 不能在构造函数或者构造成员变量时直接调用与Context
. If necessary, call it in its life cycle function.Your class inherits the Activity class, then it has a life cycle, and all logic is carried out in these life cycles. In other words, your logic code must be written in the methods of those life cycles. Generally speaking, you override the onCreate method and write page jumps there. The identifier naming of your method is also not standardized
You need to override the onCreate() method