Search code examples
javaandroidsqliteandroid-sqliteandroid-cursorloader

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


got null poiner exception at cursor.getCount(); while doing ListView using cursor loader adapter class as below

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")));
    }



}

and the cursorloader :

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) {

    }
}

cannot find the issue..please go through loader class..check query..and please help me to find the issue!


Solution

  • So ... You have a NullPointerException at the line

    return cursor.getCount();
    

    This simply means, that cursor is null. Where does cursor come from? Where is it set? The only place I see is the constructor:

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

    Now that means that the client, who is instantiating this class, does not provide an instance for the constructor parameter Cursor c. To avoid such problems, you should add a guard clause to the constructor:

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

    This will throw an NPE much earlier (at construction time) and will take you one step further. You will see that this line is causing this NPE:

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

    Caution: This line exists several times!

    So what's the problem here? Obviously FriendsCursor is null. By the way: Please stick to the Java naming conventions and let your variables start with a lower letter.

    I don't see any initialization of FriendsCursor, so this instance variable still is null, which is the cause of your problem. Initialize this variable (at the right place).