![](/img/trans.png)
[英]Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
[英]Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)
我想问一下,为什么我的代码在设备上运行时不起作用,但是当我像 Genymotion 一样在模拟器 android 上运行时,它运行良好..
有人在此链接上这样说:除非在某些情况下,否则在 super.onCreate() 之后才能调用 Activity 超类上的方法。 请将 promptsView 的初始化推迟到调用 super.onCreate() 之后。
还是没搞懂,如果有同样的问题请告诉我。。
无论如何,如果我的解释不好,我很抱歉..
public class DestinationListAdapter extends ArrayAdapter<DestinationModel> {
Context context;
int layoutResourceId;
List<DestinationModel> data = Collections.emptyList();
public DestinationListAdapter(Context context, int layoutResourceId, List<DestinationModel> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
DestinationHolder holder = null;
if(row == null)
{
// Predicted Error At Line Below
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new DestinationHolder();
holder.destination_id = (TextView) row.findViewById(R.id.destination_id);
holder.destination_name = (TextView) row.findViewById(R.id.destination_name);
row.setTag(holder);
}
else
{
holder = (DestinationHolder)row.getTag();
}
DestinationModel weather = data.get(position);
holder.destination_id.setText(weather.getDestination_id());
holder.destination_name.setText(weather.getDestination_name());
return row;
}
为了确保何时返回并继续之前的活动,我刚刚添加并检查了 getContext()!=null
这是一个很好的例子:
块前
adapter = new ExampleAdapter(getContext());
adapter.setData(items);
listView.setAdapter(adapter);
并更好地替换 getActivity()!=null
例如:
if (getActivity()!=null){
adapter = new ExampleAdapter(getActivity());
adapter.setData(items);
listView.setAdapter(adapter);
}
我认为这解决了所有与我的问题一样出现相同错误的问题!
意识到您在生命周期中的哪个位置。 getContext()
的值可能尚不可用。
例如,在DialogFragment
,在调用onCreateDialog()
之前,上下文将不可用。 所以不要尝试在构造函数中创建适配器,因为此时上下文仍然为空。
实际上,当某些东西作为空字节出现时,就会出现这个问题。 当我们使用回收器视图时,它主要出现。 因为大多数人在 RecyclerViewAdpater 的 onCreateView 中混淆了。 一些代码编写者将 Layout inflater 编写为 Tab 的布局。 但在这里我们将使用另一种布局,我们将在其中提及我们的内部 Recyclerview 布局。
view= LayoutInflater.from(mcontext).inflate(R.layout.**item_tab14**,parent,false);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.