尝试调用虚拟方法 'java.lang.Object android.content.Context.getSystemService(java.lang.String)

2024-01-09

我想问,为什么我的代码在设备上运行时不起作用,但是当我在像 Genymotion 这样的模拟器 android 上运行时,它运行得很好。

有人对此说link https://stackoverflow.com/questions/33068530/errorattempt-to-invoke-virtual-method-java-lang-object-android-content-context像这样:除非在某些情况下,否则在 super.onCreate() 之后才能调用 Activity 超类上的方法。请推迟对提示视图的初始化,直到调用 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);
}

我认为这解决了所有与我的问题有相同错误的问题!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

尝试调用虚拟方法 'java.lang.Object android.content.Context.getSystemService(java.lang.String) 的相关文章

随机推荐