本文主要是介绍在Activity中直接new Intent()报错:NullPointerException,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class MainActivity extends AppCompatActivity {public static final String TAG = "MainActivity";private Intent mIntent;//下面注释掉的代码会报nullPoiterException,因为MainActivity对象被创建时,就会调用new Intent(this,SecondActivity.class)//而new Intent()中,需要用到该MainActivity对象所attach的ContextImpl对象,该MainActivity对象所attach的ContextImpl对象是在//MainActivity对象被创建后才会被MainActivity对象所attach()【在ActivityThread.java中的performLaunchActivity()中被attach】//解决方法:1.在onCreate()中调用mIntent = new Intent(this,SecondActivity.class);因为onCreate()方法在attach()后面才会被调用。*//private Intent mIntent= new Intent(this,SecondActivity.class);*@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mIntent = new Intent(this,SecondActivity.class);}}
这篇关于在Activity中直接new Intent()报错:NullPointerException的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!