【发布时间】:2018-05-15 11:36:12
【问题描述】:
在我的一个片段中,我有时会遇到一个异常,指出我的 Context 为空。
我目前无法重现该问题,因为我尝试以多种不同方式访问崩溃的代码,但没有一致的结果。
这是我得到的崩溃日志:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: eu.side.aurora, PID: 12940
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:258)
at eu.side.aurora.views.fragments.StepStock.lambda$onCreateView$2$StepStock(StepStock.java:161)
以及引用的代码
InterventionsViewModel interventionsViewmodel = ViewmodelProviders.of(getActivity()).get(InterventionsViewModel)
interventionsViewmodel.getExceptions().observe(getActivity(), exception ->{
if(exception instanceof QuantityOverflowException){
Toast.makeText(getActivity(), "No you just can't add more stock than there is available!", Toast.LENGTH_SHORT).show();
}
if(exception instanceof ScannedArticleNotFoundException){
Toast.makeText(getActivity(), "This article doesn't even exist! Get your shit together please!²", Toast.LENGTH_SHORT).show();
}
});
奇怪的是,我在片段的 onCreateView 中几乎所有地方都引用了 getActivty() ,但它崩溃了。
要使用下面的视图访问代码,我只需按 + 或 - 按钮从我的列表中添加或删除文章。当它达到最大值时,它会发送一个Toast 以通知用户。
当点击加号或减号按钮时,它们会通知ViewModel,这将改变我之前观察到的可观察对象。
有人知道这是从哪里来的吗?我假设它来自我的片段与我的Activity 分离,但我无法弄清楚它是如何做到这一点的,因为我在创建片段后再也没有接触过它。
提前致谢, 马修
编辑:根据要求,这是完整片段的代码 包eu.side.aurora.views.fragments;
public class StepStock extends Fragment {
private INextStep nextStep;
@BindView(R.id.articles_autocomplete)
AutoCompleteTextView articlesAutocomplete;
@BindView(R.id.articles_recycler)
RecyclerView articleRecycler;
private AccountManager accountManager;
private Account account;
private ArrayList<DetailedArticle> articles;
private ArrayList<Article> stockedArticles;
private StockRecyclerAdapter stockAdapter;
private InterventionsViewModel interventionViewModel;
public StepStock() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment StepStock.
*/
// TODO: Rename and change types and number of parameters
public static StepStock newInstance() {
return new StepStock();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_step_stock, container, false);
ButterKnife.bind(this, view);
interventionViewModel = ViewModelProviders.of(getActivity()).get(InterventionsViewModel.class);
/* UI Intialization */
articleRecycler.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
/**
* Stock recycler view
* Used to keep track of stock used in an intervention
* OnPlus -> Add one from article
* OnMinus -> Remove one from article
* */
stockedArticles = new ArrayList<>();
stockAdapter = new StockRecyclerAdapter(stockedArticles, new StockRecyclerAdapter.OnArticleClickListener() {
@Override
public void onArticleClicked(int position) {
//new intent
}
@Override
public void onPlusClicked(int position) {
interventionViewModel.addOneToStockAtArticle(stockAdapter.getData().get(position));
}
@Override
public void onMinusClicked(int position) {
interventionViewModel.minusOneOrRemoveAtArticle(stockAdapter.getData().get(position));
}
});
interventionViewModel.getCurrentIntervention().observe(getActivity(), intervention -> {
if(intervention!= null && intervention.getArticles() != null)
stockAdapter.putData(intervention.getArticles());
});
interventionViewModel.getExceptions().observe(getActivity(), exception ->{
if(exception instanceof QuantityOverflowException){
Toast.makeText(getActivity(), "No you just can't add more stock than there is available!", Toast.LENGTH_SHORT).show();
}
if(exception instanceof ScannedArticleNotFoundException){
Toast.makeText(getActivity(), "This article doesn't even exist! Get your shit together please!²", Toast.LENGTH_SHORT).show();
}
});
return view;
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if(context instanceof INextStep){
nextStep = (INextStep) context;
}
else{
throw new RuntimeException(context.toString() + " must implement INextStep");
}
}
@Override
public void onDetach() {
super.onDetach();
nextStep = null;
}
}
【问题讨论】:
-
请张贴片段代码。
-
@SushobhNadiger 我刚刚相应地更新了帖子
-
我认为你不应该在 onCreate 中调用 getActivity。在创建 Activity 之前,可能会创建您的视图。稍后再尝试。
标签: android android-fragments android-context