get clicked item from listview
Asked Answered
L

7

11

I've got a problem. Before modification in my XML file, my listview was able to work perfectly. But now, after some modifications in xml, its not working properly. My listview is custom. So, i've created separate xml to render every single row in the listview.

My single row.xml code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:id="@+id/relativeLayoutSingleRowManageAddictions"
    android:layout_height="40dp"
    android:background="@drawable/box_midbg" >

    <TextView
        android:id="@+id/textViewSingleRowManageAddictions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="17dp"
        android:text="TextView"
        android:textSize="20dp"
        android:textColor="#ffffff" />

    <ImageView
        android:id="@+id/imageViewSingleRowManageAddictions"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="18dp"
        android:src="@drawable/listing_arrow" />

</RelativeLayout>

My main.xml code where listview resides:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/main_bg_edited" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        style="@style/top_bar_style" >

        <ImageView
            android:id="@+id/imageViewMAnageAddictionsBack"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:src="@drawable/back_arrow"
            android:clickable="true" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/header_style"
            android:text="Manage Addictions" />

        <ImageView
            android:id="@+id/imageViewManageAddictionsAdd"
            android:layout_width="25dp"
            android:layout_height="20dp"
            android:layout_marginRight="3dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/plus_nav"
            android:clickable="true" />

    </RelativeLayout>

    <ListView
        android:id="@+id/listViewManageAddictions"
        android:layout_width="290dp"
        android:layout_height="fill_parent"
        android:layout_below="@+id/relativeLayout1"
        android:layout_centerHorizontal="true"
        android:layout_centerInParent="true"
        android:layout_marginTop="12dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="2dp" />

</RelativeLayout>

And my java code for it:

package com.addictioncounterapp;

import java.util.ArrayList;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class ManageAddictionList extends Activity {
  ImageView iv_manage_addictions_back, iv_manage_addictions_add;
  ListView listview;
  ArrayList < String > arraylist_manage_addiction;
  ArrayAdapter < String > arrayadapter_manage_addiction;
  SQLiteDatabase database;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manage_addiction_list);

    loaddatabase();

    iv_manage_addictions_back = (ImageView) findViewById(R.id.imageViewMAnageAddictionsBack);
    iv_manage_addictions_back.setClickable(true);
    iv_manage_addictions_back.setOnClickListener(new OnClickListener() {@Override
      public void onClick(View v) {
        startActivity(new Intent(ManageAddictionList.this, Settings.class));
      }
    });

    iv_manage_addictions_add = (ImageView) findViewById(R.id.imageViewManageAddictionsAdd);
    iv_manage_addictions_add.setClickable(true);
    iv_manage_addictions_add.setOnClickListener(new OnClickListener() {@Override
      public void onClick(View v) {
        Intent intent = new Intent(ManageAddictionList.this, MainActivity.class);
        intent.putExtra("name", "");
        intent.putExtra("unit", "");
        intent.putExtra("attribute", "");
        intent.putExtra("limit", "");
        intent.putExtra("operation", "Add Addiction");
        startActivity(intent);
      }
    });


    arraylist_manage_addiction = new ArrayList < String > ();
    manageList();
    listview = (ListView) findViewById(R.id.listViewManageAddictions);

    if (arraylist_manage_addiction.isEmpty()) Toast.makeText(getBaseContext(), "No Addictions found to manage. Click on 'add' button to create new Addiction.", Toast.LENGTH_SHORT)
      .show();
    else listview.setAdapter(arrayadapter_manage_addiction);

    listview.setOnItemClickListener(new OnItemClickListener() {@Override
      public void onItemClick(AdapterView <? > arg0, View arg1, int arg2, long arg3) {
        String name = null, attribute = null, unit = null, limit = null;

        View parentView = (View) arg0.getParent();
        name = ((TextView) parentView.findViewById(R.id.textViewSingleRowManageAddictions))
          .getText() + "";

        Toast.makeText(getBaseContext(), name, Toast.LENGTH_SHORT)
          .show();

        int cat_id = 0;

        //--------Fetching cat_id through name from the list--------

        Cursor cursor;

        cursor = database.query("category", new String[] {
          "cat_id"
        }, new String("cat_name=?"), new String[] {
          name
        }, null, null, null);

        if (cursor.getCount() > 0) {
          while (cursor.moveToNext())
          cat_id = cursor.getInt(0);
          cursor.close();
        }

        //--------Fetching unit, attribute, limit through cat_id from the list--------

        cursor = database.query("category_attribute", new String[] {
          "cat_attribute_name", "cat_attribute_unit", "cat_limit"
        }, new String("cat_id=?"), new String[] {
          cat_id + ""
        }, null, null, null);

        if (cursor.getCount() > 0) {
          while (cursor.moveToNext()) {
            attribute = cursor.getString(0);
            unit = cursor.getString(1);
            limit = cursor.getString(2);
          }
          cursor.close();
        }

        Intent intent = new Intent(ManageAddictionList.this, MainActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("unit", unit);
        intent.putExtra("attribute", attribute);
        intent.putExtra("limit", limit);
        intent.putExtra("cat_id", cat_id);
        intent.putExtra("operation", "Edit Addiction");
        startActivity(intent);
      }
    });
  }

  private void loaddatabase() {
    database = openOrCreateDatabase("AddictionCounter.db", SQLiteDatabase.OPEN_READONLY, null);
  }

  private void manageList() {
    String[] columns = {
      "cat_name"
    };
    Cursor cursor;

    cursor = database.query("category", columns, null, null, null, null, null);

    if (cursor.getCount() > 0) {
      while (cursor.moveToNext())
      arraylist_manage_addiction.add(cursor.getString(0));
      cursor.close();
    }

    arrayadapter_manage_addiction = new ArrayAdapter < String > (this, R.layout.single_row_manage_addictions, R.id.textViewSingleRowManageAddictions, arraylist_manage_addiction);
  }
}

The main bug behind this is that, when I get the name using this:

View parentView = (View) arg0.getParent();
name = ((TextView) parentView.findViewById(R.id.textViewSingleRowManageAddictions)).getText()+"";

the listview of any record, it gives the name of first record only. For example, if my first row has textview named "Gaming", when i click on any row, (for debugging purpose, i used Toast.makeText(...)) it Toasts "Gaming" as the name for every record in the listview, though every record in the listview is unique. Please help me out with this.

Loveland answered 15/2, 2013 at 8:53 Comment(3)
arg0 is your ListView ... use arg1 which is your clicked row ...Sanctitude
... anyway for only GETTING clicked item is better to use String name = (String)agr0.getAdapter().getItem(arg2);Sanctitude
@Sanctitude you are right. I got it. Appreciated.Loveland
T
56
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        // selected item
        String selected = ((TextView) view.findViewById(R.id.your_textView_item_id)).getText().toString();

        Toast toast = Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT);
        toast.show();
    }
});
Tidy answered 15/2, 2013 at 9:4 Comment(1)
Nice.. answer but how to get different item click event in onItemClick. In my listview there are 5 item i want perform event on different item cilck.. thanksIntercostal
P
4
listView = (ListView)view.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String selected = ((TextView) view.findViewById(R.id.complaint)).getText().toString();
        Toast.makeText(context,selected,Toast.LENGTH_LONG).show();
    }
});
Photosphere answered 9/6, 2016 at 10:24 Comment(0)
S
2

If you want onClickListener on the TextView only, its better to define onClickListener in the Adapter itself. like

yourTextView.setOnClickListener(new View.OnClickListener() {
      public void onClick(View v) {
        // showToast()
      }
});
Strategy answered 15/2, 2013 at 9:0 Comment(1)
Your method is appreciable too. But i needed to imply listener on whole list record itself, not just textview inside it. Your opinion is also true, in certain cases, agreed...Loveland
S
1

Apart from the above solution, this worked for me i was facing a similar situation, I was able to solve it after i added the following

android:descendantFocusability="blocksDescendants"

to my listview in xml. It is working now. To the real curious user here's more info about that http://developer.android.com/reference/android/R.attr.html#descendantFocusability

Salesperson answered 24/12, 2014 at 4:30 Comment(1)
nice alternate way, didn't know about this. I was struggling a lot with list view and its child.Crap
N
0

Because i have not enough reputation to comment Here i am commenting on your question on the answer of SKK Just add if statement to your and perform different actions...

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

    // selected item
    String selected = ((TextView) view.findViewById(R.id.your_textView_item_id)).getText().toString();

    if(selected.equals("Your comparing string, like Games"){                                               

    Toast toast = Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT);
    toast.show(); }                                                                                                                 

    else {                                            
    if(selected.equals("Your comparing string, like Games")){                                            
    Toast toast = Toast.makeText(getApplicationContext(), selected, Toast.LENGTH_SHORT);
    toast.show();}}


}});                                                   
Neurosis answered 30/11, 2017 at 8:23 Comment(0)
L
0
ArrayList list=new ArrayList();
//..Removing BlueTooth Specific code(Paired Devices) for brevity

 for (BluetoothDevice bt : pairedDevices) list.add(bt.getName());
//populate the ArrayList

final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
//This ArrayAdapter  will be used for the ListView(lv)
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //String selected = ((TextView) view.findViewById(R.id.textView)).getText().toString();
                    Toast.makeText(getApplicationContext(), (String) arLis.get(position), Toast.LENGTH_LONG).show();
                }
            });
//use the Clicked item at "position" from the original ArrayList (arLis)
//This works
//Do we always have the Original ArrayList used to generate the ListView i //guess  That is the question
Laverne answered 6/3, 2022 at 17:27 Comment(0)
T
0

To recover a typed object from selected index:

public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
  ArrayAdapter<CustomType> adapter = this.adapter
  CustomType item = adapter.getItem(position);
}
Twowheeler answered 15/8, 2022 at 21:16 Comment(1)
Please read How do I write a good answer?. While this code block may answer the OP's question, this answer would be much more useful if you explain how this code is different from the code in the question, what you've changed, why you've changed it and why that solves the problem without introducing others.Sacken

© 2022 - 2024 — McMap. All rights reserved.