NullPointerException:Attempt 在空对象引用上调用虚拟方法 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'

NullPointerException:Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference

所以,我在 activity 中做 2 个片段,1 个片段使用 listview+array 适配器。 但是当我尝试创建适配器的实例时它是空的。 我看到其他人遇到同样的问题,但对他们有用的方法对我不起作用。 这也是我自己制作的第一个应用程序,如果我很笨,请不要生气

MyFragment.onCreateView

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView =inflater.inflate(R.layout.fragment_todo, container, false);
    ListView listView = rootView.findViewById(R.id.list_view);


    ArrayList<Task> arrayList = new ArrayList<>();
    arrayList.add(new Task("this is a placeholder todo",Task.PRIORITY_LOW, new Date()));
    arrayList.add(new Task("this is a placeholder todo",Task.PRIORITY_MEDIUM, new Date()));
    arrayList.add(new Task("this is a placeholder todo",Task.PRIORITY_HIGH, new Date()));


    listView.setAdapter(new HomeActivity.TaskAdapter(getActivity(), arrayList,rootView));

    ViewModel viewModel = ViewModelProviders.of(this).get(ViewModel.class);
    viewModel.getTasks().observe(this, new Observer<List<Task>>() {
        @Override
        public void onChanged(@Nullable List<Task> taskEntries) {
            //TODO SET THE ADAPTER
        }
    });

    return rootView;
}

MyMainActivity 也包含适配器:

public class HomeActivity extends FragmentActivity {


static int colorGreen ;
static int colorOrange;
static int colorRed;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    colorGreen=HomeActivity.this.getResources().getColor(R.color.colorGreen);
    colorOrange=HomeActivity.this.getResources().getColor(R.color.colorOrange);
    colorRed=HomeActivity.this.getResources().getColor(R.color.colorPrimaryDark);


    //FAB
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    initializeAds();
    DataBase Db = DataBase.getInstance(getApplicationContext());

   ViewPager vp = findViewById(R.id.view_pager);
    CustomFragmentPageAdapter myAdapter = new CustomFragmentPageAdapter(getSupportFragmentManager(),this);
   vp.setAdapter(myAdapter);

  TabLayout mTabLayout = findViewById(R.id.tabLayout_Home);
   mTabLayout.setupWithViewPager(vp);


}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_home, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


public static class TaskAdapter extends ArrayAdapter<Task> {

    private View rootView;

    public TaskAdapter(Activity context, ArrayList<Task> tasks ,View view) {
        super(context, 0, tasks );
        rootView=view;


    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        // Check if the existing view is being reused, otherwise inflate the view

        if (convertView == null) {
            convertView = rootView;

        }
        Task currentTask = getItem(position);

        TextView description = convertView.findViewById(R.id.description_todo);
        if (currentTask != null) {
            description.setText(currentTask.getDescription());
        }

        TextView date = convertView.findViewById(R.id.date_todo);
        if (currentTask != null) {
            date.setText(currentTask.getUpdatedAt().toString());
        }

        ConstraintLayout constraintLayout = convertView.findViewById(R.id.constraint_layout_todo);
        if (currentTask != null) {
            switch (currentTask.getPriority()){
                case Task.PRIORITY_LOW:constraintLayout.setBackgroundColor(colorGreen);
                case Task.PRIORITY_MEDIUM:constraintLayout.setBackgroundColor(colorOrange);
                case Task.PRIORITY_HIGH:constraintLayout.setBackgroundColor(colorRed);
            }
        }

        return convertView;
    }
}

对我来说,您的代码看起来没问题。但是,可能会发生错误,因为您的 fragment_todo.

中可能存在问题

我以前 运行 多次遇到同样的错误。所以,检查一下。

明白错误是告诉你 ListViewnull。大多数时候,这意味着您的代码中可能存在拼写错误或类似内容。

Make sure the id in your XML matches with the one in your Fragment class.

希望对您有所帮助。