Your activity/fragment is not yet attached to Application. You cant request ViewModel before onCre

Android Studio 报错:
… Your activity/fragment is not yet attached to Application. You can’t request ViewModel before onCreate call.

原代码:

public class MainActivity extends AppCompatActivity{
	MyViewModel myViewModel= ViewModelProviders.of(this).get(myViewModel.class);//这一句有问题
	protected void onCreate(Bundle savedInstanceState) {
		//...
		myViewModel.func();
    }
}

是ViewModel初始化的问题

【解决】:把定义和初始化分离,初始化放到onCreate里面:

public class MainActivity extends AppCompatActivity{
	MyViewModel myViewModel; //在这里分离原本等号左右的代码,右边部分放到onCreate里面 
	protected void onCreate(Bundle savedInstanceState) {
		//...
		myViewModel = ViewModelProviders.of(this).get(myViewModel.class);
        myViewModel.func();
    }
}

你可能感兴趣的:(android)