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

2022-09-02 23:20:30

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

有人像这样在这个链接上说:除非在某些情况下,否则在super.onCreate()之后,你不能在Active超类上调用方法。请推迟对 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;
    }

答案 1

确保当返回并继续以前的活动时,我只是添加并检查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);
}

我认为这已经解决了所有问题,这些问题与我的问题一样得到了相同的错误!


答案 2

注意您在生命周期中所处的位置。的值可能尚不可用。getContext()

例如,在 中,上下文在被调用之前将不可用。因此,不要尝试在构造函数中创建适配器,因为此时上下文仍将为 null。DialogFragmentonCreateDialog()


推荐