空对象引用上的 int android.database.Cursor.getCount()'

int android.database.Cursor.getCount()' on a null object reference

cursor.getCount(); 出现空指针异常 在使用游标加载器执行 ListView 时 适配器 class 如下

public class FriendsListCursorAdapter extends CursorAdapter  {
    private Cursor cursor;
    final VROPreferenceManager preferenceManager = new VROPreferenceManager();
    Context con;
    public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
          super(context,c,true);
        cursor = c;
        con=context;
    }


    public void addItems(Cursor newItems) {
        if (0 == newItems.getCount()) {
            return;
        }


        notifyDataSetChanged();
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return cursor.getCount();
    }


    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }


    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.vro_contact_view, null);
        bindView(view, context, cursor);
        return view;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

        TextView txtID = (TextView) view.findViewById(R.id.text_fname_lname);
        txtID.setText(cursor.getString(cursor.getColumnIndex("first_name")));
      //  VROUser user =cursor.getColumnIndex("first_name");

         // / ColCode
        TextView txtCode = (TextView) view.findViewById(R.id.text_email);
        txtCode.setText(cursor.getString(cursor.getColumnIndex("email")));
        ImageView profilePic = (ImageView) view.findViewById(R.id.user_image);

        cursor.getColumnIndex("user_profile_pic");
      view.findViewById(R.id.ColCountry);
        //txtCountry.setText(cursor.getString(cursor.getColumnIndex("Country")));
    }



}

和光标加载器:

public class FindPeopleFragment extends BaseFragment implements LoaderCallbacks<Cursor> {

    public FindPeopleFragment() {
    }

    private TextView advancedSearchOption;
    private TextView saerchButton;
     EndlessListView listUsers;
    private EditText searchWord;
    private EditText searchFirstName;
    private EditText searchLastName;
    private EditText searchEmail;
    private EditText searchCountry;
    private EditText searchState;
    private int offset = 0;
    private final int limit = 30;
    private boolean mHaveMoreDataToLoad = true;
    private VROAccountManager manager;
    private ArrayList<VROUser> postsList = new ArrayList<>();
    private View advanced;
    private Cursor FriendsCursor;

    // Cursor  c;
    private TextView description;
   Object friend_name;
    FriendsListCursorAdapter FRIEND_ADAPTER;
DatabaseHelper dh;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        title = "My Friends";
//      setSelection(0);

    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView != null) {

            ((ViewGroup) rootView.getParent()).removeView(rootView);
            return rootView;
        }

        rootView = inflater.inflate(R.layout.fragment_find_people, null);
        getLoaderManager().initLoader(1, null, this);
        progressBar = rootView.findViewById(R.id.progressBar);
        saerchButton = (TextView) rootView.findViewById(R.id.button_search);
        listUsers = (EndlessListView) rootView.findViewById(R.id.user_list);
        searchWord = (EditText) rootView
                .findViewById(R.id.editText_search_word);
        searchFirstName = (EditText) rootView
                .findViewById(R.id.editText_search_first_name);
        searchLastName = (EditText) rootView
                .findViewById(R.id.editText_search_last_name);
        searchEmail = (EditText) rootView
                .findViewById(R.id.editText_search_email);
        searchCountry = (EditText) rootView
                .findViewById(R.id.editText_search_country);
        searchState = (EditText) rootView
                .findViewById(R.id.editText_search_state);
        advancedSearchOption = (TextView) rootView
                .findViewById(R.id.advancedSearch);
        advancedSearchOption.setVisibility(View.GONE);
        manager = new VROAccountManager(getActivity());
        advanced = rootView.findViewById(R.id.layout_advanced_search);
        description = (TextView) rootView.findViewById(R.id.description);
        description
                .setText("You are friends with the following users. To find new friends or to view friends request sent or received use the menu on right");
 FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
        FriendsCursor, true);
       // loadMoreData();


        saerchButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                listUsers.setAdapter(FRIEND_ADAPTER);


            }
});
        listUsers.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
               friend_name=listUsers.getSelectedItem();
                Toast.makeText(getActivity(), " "+friend_name, Toast.LENGTH_SHORT).show();
//                Intent intent = new Intent(getActivity(), ProfileViewActivity.class);
//                intent.putExtra("userId",(int)friend_name);
//                getActivity().startActivity(intent);

            }
        });
        return rootView;
    }

    private HashMap<String, String> data = new HashMap<>();


    private final EndlessListView.OnLoadMoreListener loadMoreListener = new EndlessListView.OnLoadMoreListener() {

        @Override
        public boolean onLoadMore() {
            if (true == mHaveMoreDataToLoad) {
                //loadMoreData();
            }
            // else {
            // Toast.makeText(getActivity(), "No more data to load",
            // Toast.LENGTH_SHORT).show();
            // }

            return mHaveMoreDataToLoad;
        }

        @Override
        public void onReachedTop(boolean isTop) {
            // TODO Auto-generated method stub

        }
    };
    private final Handler handler = new Handler();
    private View progressBar;





    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {

        String[] projection = { FriendinfoTable.Cols.ID,FriendinfoTable.Cols.FIRST_NAME,
                FriendinfoTable.Cols.LAST_NAME,FriendinfoTable.Cols.USER_NAME,FriendinfoTable.Cols.EMAIL,
                FriendinfoTable.Cols.USER_PROFILE_PIC,FriendinfoTable.Cols.USER_TIMELINE_PIC,
                FriendinfoTable.Cols.COUNTRY,FriendinfoTable.Cols.STATE,FriendinfoTable.Cols.CITY,
                FriendinfoTable.Cols.ABOUT,FriendinfoTable.Cols.GENDER,FriendinfoTable.Cols.DATEOFBIRTH,
                FriendinfoTable.Cols.FRIENDSHIP_STATUS,FriendinfoTable.Cols.QUICKBLOX_ID};


        CursorLoader cursorLoader = new CursorLoader(getActivity(),
                FriendinfoTable.CONTENT_URI, projection, null, null, null);

        return cursorLoader;
    }


    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        FriendsCursor = data;
        if (FRIEND_ADAPTER == null) {
            FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(),
                    FriendsCursor, true);
            listUsers.setAdapter(FRIEND_ADAPTER);
        } else {
            FRIEND_ADAPTER.swapCursor(FriendsCursor);

        }
    }enter code here

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }
}

找不到问题..请通过加载器 class..检查查询..请帮我找到问题!

所以...你在第

行有一个NullPointerException
return cursor.getCount();

这只是意味着,cursornullcursor 从哪里来?它在哪里设置?我唯一看到的地方是构造函数:

public class FriendsListCursorAdapter extends CursorAdapter  {
    private Cursor cursor;
    ...
    public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
        super(context, c, true);
        cursor = c;
        con = context;
    }
    ...
}

现在这意味着正在实例化此 class 的 客户端 没有为构造函数参数 Cursor c 提供实例。为了避免此类问题,您应该在构造函数中添加一个保护子句

public FriendsListCursorAdapter(Context context, Cursor c, boolean b) {
    super(context, c, true);
    cursor = Objects.requireNonNull(c);
    con = Objects.requireNonNull(context);
}

这会更早地(在构建时)抛出 NPE,并且会让你更进一步。您将看到此行导致此 NPE:

FRIEND_ADAPTER = new FriendsListCursorAdapter(getActivity(), FriendsCursor, true);

注意:此行存在多次!

那么这里有什么问题呢?很明显FriendsCursor就是null。顺便说一句:请坚持 Java naming conventions 并让您的变量以小写字母开头。

我没有看到 FriendsCursor 的任何初始化,所以这个实例变量仍然是 null,这就是你的问题的原因。初始化这个变量(在正确的地方)。

你的游标为空,因此抛出空指针异常 尝试处理游标 nullpointerexception

public int getCount() {
    // TODO Auto-generated method stub
    //try using this
    if(cursor==null)
       return 0;
    return cursor.getCount();
}