Unable to invoke the onItemClick() method for ListView

  • Replies:0
Nitin Mittal
  • Forum posts: 1

Sep 5, 2017, 6:48:25 PM via Website

Friends,

I have created a ListView using android studio using a customAdapter. I want a callback method whenever an item in the list is clicked. However that doesn't seem to work at all. Please help identify where exactly the cause may be.

I am posting my code fragments below. Any advice would be helpful.
The Layout

        <ListView
        android:id="@+id/callsListView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

Callback Method

     ListView callsList = (ListView) findViewById(R.id.callsListView);
    CustomAdapter customAdapter = new CustomAdapter(DataUtil.getCallsData(getContentResolver(),
            Settings.getSettings(getSharedPreferences("MyDNDPreferences", MODE_PRIVATE))),
            this.getApplicationContext(),
            R.layout.call_row);

    callsList.setAdapter(customAdapter);
    callsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_SHORT).show();
        }
    });

getView() mthod of my Custom Adapter

    @Override
public View getView(int position, View convertView, final ViewGroup parent) {

    try {
        // Get the data item for this position
        final CommunicationDetail dataModel = dataSet.get(position);
        // Check if an existing view is being reused, otherwise inflate the view
        ViewHolder viewHolder; // view lookup cache stored in tag
        final View result;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(this.layout, parent, false);
            viewHolder.txtName = (TextView) convertView.findViewById(R.id.name);
            viewHolder.txtTime = (TextView) convertView.findViewById(R.id.time);
            if (this.layout == R.layout.msg_row) {
                viewHolder.txtMsg = (TextView) convertView.findViewById(R.id.msg);
            }
            result = convertView;
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
            result = convertView;
        }
    lastPosition = position;
        viewHolder.txtName.setText(dataModel.getName());
        viewHolder.txtTime.setText(dataModel.getDate());
        if (this.layout == R.layout.msg_row) {
            viewHolder.txtMsg.setText(dataModel.getMessage());
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return convertView;

Reply