Try invoking the virtual method 'int java.util.ArrayList.size ()' on a null object reference (using with adapter, fragment and activity)

advertisements

This question already has an answer here:

  • What is a NullPointerException, and how do I fix it? 12 answers

I am getting this error-Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
This is what i have done!

PeopleListFragment

 **PeopleListFragment** 

public class PeopleListFragment extends Fragment{

    public static final String DISPLAY_URL = ServiceAPI.URL_CONTACTS;

    private static final String TAG = "PeopleListActivity";

    public static final boolean DEBUG = Constant.DEBUG;

    private ProgressDialog progressDialog;

    public PeopleAdapter  adapter;

    private GetAllPeopleTask mGetAllPeople = null;

    private Intent intent;

    public static ListView mContactlistView;

    public PeopleListFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_people_list, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mContactlistView = (ListView) view.findViewById(R.id.people_list);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        List<People> contactList = new ArrayList<People>();

        adapter = new PeopleAdapter(getActivity().getApplicationContext(),
                R.layout.people_list_item, contactList);

        mContactlistView.setAdapter(adapter);

        mContactlistView.setTextFilterEnabled(true);
        mContactlistView.setFastScrollEnabled(true);

        mContactlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String empId = String.valueOf(adapter.getItem(position).getEmployeeId());
                String name = String.valueOf(adapter.getItem(position).getFirstName());

                intent = new Intent(getActivity(),
                        PeopleDetailsActivity.class);

                intent.putExtra("EmployeeId", empId);

                intent.putExtra("name", name);

                startActivity(intent);
            }
        });

        startAsyncTask();

        TextView textView = new TextView(getContext());
        textView.setText("Empty");

        mContactlistView.setEmptyView(textView);
    }

    public void startAsyncTask() {
        mGetAllPeople = new GetAllPeopleTask();
        mGetAllPeople.execute(DISPLAY_URL, "12345678");
    }

    public class GetAllPeopleTask extends AsyncTask<String, Void, List<People>> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading");
            progressDialog.show();
        }

        @Override
        protected ArrayList<People> doInBackground(String... params) {

            ArrayList<People> peopleList = new ArrayList<>();

            try {

                URL url = new URL(params[0]);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

                httpURLConnection.setReadTimeout(40000);
                httpURLConnection.setConnectTimeout(50000);

                httpURLConnection.setRequestMethod("POST");

                httpURLConnection.setRequestProperty("Content-Type", "application/json");
                httpURLConnection.setRequestProperty("Accept", "application/json");

                httpURLConnection.setDoOutput(true);

                JSONObject request = new JSONObject();

                request.put("session", params[1]);

                String bodyParams = request.toString();

                if (DEBUG) {

                    Log.i(TAG, bodyParams);
                }
                httpURLConnection.setRequestProperty("Content-Length",
                        String.valueOf(bodyParams.getBytes().length));

                DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());

                outputStream.writeBytes(bodyParams);
                outputStream.flush();
                outputStream.close();

                httpURLConnection.connect();

                if (httpURLConnection.getResponseCode() == 200) {
                    Log.i(TAG, "Success");
                } else {
                    Log.i(TAG, "Error  Code :" + httpURLConnection.getResponseCode());
                }

                InputStream inputStream = httpURLConnection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;

                StringBuilder builder = new StringBuilder();

                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                Log.i(TAG, "Builder String : " + builder.toString());

                JSONObject jsonObject = new JSONObject(builder.toString());

                Log.i(TAG, "Response JSON : " + jsonObject.toString());

                if (jsonObject.has("responseData")) {
                    JSONArray responseDataArr = jsonObject.optJSONArray("responseData");

                    for (int i = 0; i < responseDataArr.length(); i++) {
                        JSONObject peopleJSON = responseDataArr.optJSONObject(i);

                        People people = new People();

                        people.setEmployeeId(peopleJSON.optString("employeeId"));
                        people.setFirstName(peopleJSON.optString("firstName"));
                        people.setLastName(peopleJSON.optString("lastName"));

                       //  Log.i("hebsiba ", "People first name" + people.getFirstName() + ", last name is " + people.getLastName()) ;

                        if((!people.getFirstName().isEmpty()) && (!people.getLastName().isEmpty())) {
                            peopleList.add(people);
                        }

                        if (DEBUG) {
                            Log.i(TAG, "People " + people.getEmployeeId());
                        }
                    }
                }

            } catch (IOException | JSONException e) {
                Log.e(TAG, e.toString());
            }

            return peopleList;
        }

        @Override
        protected void onPostExecute(List<People> people) {

            super.onPostExecute(people);

            Collections.sort(people, new Comparator<People>() {
                @Override
                public int compare(People lhs, People rhs) {
                    return lhs.getFirstName().compareToIgnoreCase(rhs.getFirstName());
                }
            });

            adapter.addAll(people);

            if (DEBUG) {
                Log.i(TAG, adapter.getCount() + " ");
            }

            Log.v(TAG, String.valueOf(people.size()));

            progressDialog.dismiss();
        }
    }

}

This is the PeopleAdapter

 **PeopleAdapter** 

public class PeopleAdapter extends ArrayAdapter<People> implements Filterable {

    private PeopleListActivity activity;
    private PeopleFilter peopleFilter;

    private List<People> peopleList;
    private List<People> filteredList;

    public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
        super(applicationContext, people_list_item, contactList);

        filteredList =  contactList;
        getFilter();
    }

    @Override
    public int getCount() {
        return filteredList.size();
    }

    @Override
    public People getItem(int i) {
        return filteredList.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        People peopleList = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.people_list_item, null);
            holder = new ViewHolder();

            holder.firstName = (TextView) convertView.findViewById(R.id.firstName);
            holder.lastName = (TextView) convertView.findViewById(R.id.lastName);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.firstName.setText(peopleList.getFirstName());
        holder.lastName.setText(peopleList.getLastName());

        return convertView;
    }

    /**
     * Get custom filter
     * @return filter
     */
    @Override
    public Filter getFilter() {
        if (peopleFilter == null) {
            peopleFilter = new PeopleFilter();
        }

        return peopleFilter;
    }

    static class ViewHolder {
        TextView firstName;
        TextView lastName;
    }

    private class PeopleFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();
            if (constraint!=null && constraint.length()>0) {
                ArrayList<People> tempList = new ArrayList<>();

                // search content in friend list
                for (People user : peopleList) {
                    if (user.getFirstName().toLowerCase().contains(constraint.toString().toLowerCase())) {
                        tempList.add(user);
                    }
                }

                filterResults.count = tempList.size();
                filterResults.values = tempList;
            } else {
                filterResults.count = peopleList.size();
                filterResults.values = peopleList;
            }

            return filterResults;
        }

        /**
         * Notify about filtered list to ui
         * @param constraint text
         * @param results filtered result
         */
        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
            filteredList = (ArrayList<People>) results.values;
            notifyDataSetChanged();
        }
    }

}

And this is PeopleListActivity

**PeopleListActivity** 

public class PeopleListActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {

    private PeopleListFragment fragment;
    private FragmentManager displayFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.argb(255, 180, 110, 60));
        }

        setContentView(R.layout.activity_people);

        Toolbar toolbar = (Toolbar) findViewById(R.id.people_toolbar);
        setSupportActionBar(toolbar);

        toolbar.setNavigationIcon(R.drawable.ic_back_arrow);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PeopleListActivity.this, NavigationActivity.class);
                startActivity(intent);
            }
        });

        displayFragment = getSupportFragmentManager();

        fragment = new PeopleListFragment();

        displayFragment.beginTransaction().add(R.id.people_fragment, fragment).commit();

        if (savedInstanceState == null) {

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.options_menu, menu);

        SearchManager searchManager =(SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView =(SearchView) menu.findItem(R.id.search).getActionView();

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

//        searchView.setIconifiedByDefault(false);
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return true;

//     return super.onCreateOptionsMenu(menu);

    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        PeopleAdapter peopleAdapter = (PeopleAdapter) PeopleListFragment.mContactlistView.getAdapter();
       peopleAdapter.getFilter().filter(newText);

        return true;

    }
}

Could anyone help me with this..?


Assign some value to filteredList when you create the Adapter

Example:

public PeopleAdapter(Context applicationContext, int people_list_item, List<People> contactList) {
    super(applicationContext, people_list_item, contactList);
    filteredList = contactList;
    getFilter();
}