How to get id of particular item of listview in android?

22,653

Solution 1

Try with below code:

public class Adapter1 extends BaseAdapter implements OnClickListener {
    public ArrayList<HashMap<String, String>> arr = null;
    Context context = null;
    LayoutInflater layoutInflater = null;
    HashMap<String, String> getData = new HashMap<String, String>();

    String urlLike = null;
    TextView strId = null;

    public NewsFeedAdapter(Context context,
            ArrayList<HashMap<String, String>> arr) {
        this.context = context;
        this.arr= arr;
        layoutInflater = LayoutInflater.from(context);
    }

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

    @Override
    public Object getItem(int position) {
        return arr.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = layoutInflater.inflate(
                    R.layout.my_list_item, null);
            /** initialize ViewHolder */
            viewHolder = new ViewHolder();

            /** Initialize Widgets */
            /** Imageview */

            viewHolder.imgLike = (ImageView) convertView
                    .findViewById(R.id.imgLike);


            viewHolder.imgComments = (ImageView) convertView
                    .findViewById(R.id.imgComments);
            viewHolder.imgComments.setOnClickListener(this);

            viewHolder.imgShare = (ImageView) convertView
                    .findViewById(R.id.imgShare);
            viewHolder.imgShare.setOnClickListener(this);

            /** TextView */
            viewHolder.txtId = (TextView) convertView
                    .findViewById(R.id.txtId);

            viewHolder.txtDescription = (TextView) convertView
                    .findViewById(R.id.txtDescription);

            getData = arr.get(position);
            viewHolder.txtId.setText(getData
                    .get(Fragment1.TAG_ID));

            viewHolder.txtDescription.setText(getData
                    .get(Fragment1.TAG_MESSAGE));

            convertView.setTag(viewHolder);

        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        convertView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {               

            }
        });

         viewHolder.imgLike.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {               
                strId=arr.get(position).getId();//or whatever you want to do do here.
            }
        });

        return convertView;
    }

    /** ViewHolder Class */
    public class ViewHolder {
        ImageView imgLike = null, imgComments = null,
                imgShare = null;
        TextView txtId = null,txtDescription = null;
    }
}

Solution 2

You need to initialize strId in getView()

here in the following code, its not able to initialize it based on "view" object, hence you get nullpointer.

case R.id.imgLike:
    strId = ((TextView) view.findViewById(R.id.txtId));

mark as solved if you find the answer useful.

Solution 3

Try this:

strId = (TextView) view.getParent().findViewById(R.id.txtId);

This will fix your crash, but you need to rethink about your design.

Solution 4

What u have to do is set Diff onclick Listeners on diff views

viewHolder.txtDescription.setTag(R.id.txtDescription,position);
viewHolder.txtDescription.setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View v) {
        int position_clicked=(Integer)v.getTag();               
    }
});

repeat it for every view your want to set listener

Share:
22,653
Reena
Author by

Reena

Updated on November 25, 2020

Comments

  • Reena
    Reena over 3 years

    I am using Listview and set the multiple item and each item have Like, share and comment option. Actually I have fetch the Item Id and also setText of TextView, Its Successfully. But Not able to get Item Id on Like Button Click event for particular item. How to fetch Item Id for every items in Listview on Button Click Event?

    Demo for MyAdapter Class:

    public class Adapter1 extends BaseAdapter implements OnClickListener {
        public ArrayList<HashMap<String, String>> arr = null;
        Context context = null;
        LayoutInflater layoutInflater = null;
        HashMap<String, String> getData = new HashMap<String, String>();
    
        String urlLike = null;
        TextView strId = null;
    
        public NewsFeedAdapter(Context context,
                ArrayList<HashMap<String, String>> arr) {
            this.context = context;
            this.arr= arr;
            layoutInflater = LayoutInflater.from(context);
        }
    
        @Override
        public int getCount() {
            return arr.size();
        }
    
        @Override
        public Object getItem(int position) {
            return arr.get(position);
        }
    
        @Override
        public long getItemId(int position) {
            return position;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(
                        R.layout.my_list_item, null);
                /** initialize ViewHolder */
                viewHolder = new ViewHolder();
    
                /** Initialize Widgets */
                /** Imageview */
    
                viewHolder.imgLike = (ImageView) convertView
                        .findViewById(R.id.imgLike);
                viewHolder.imgLike.setOnClickListener(this);
    
                viewHolder.imgComments = (ImageView) convertView
                        .findViewById(R.id.imgComments);
                viewHolder.imgComments.setOnClickListener(this);
    
                viewHolder.imgShare = (ImageView) convertView
                        .findViewById(R.id.imgShare);
                viewHolder.imgShare.setOnClickListener(this);
    
                /** TextView */
                viewHolder.txtId = (TextView) convertView
                        .findViewById(R.id.txtId);
    
                viewHolder.txtDescription = (TextView) convertView
                        .findViewById(R.id.txtDescription);
    
                getData = arr.get(position);
                viewHolder.txtId.setText(getData
                        .get(Fragment1.TAG_ID));
    
                viewHolder.txtDescription.setText(getData
                        .get(Fragment1.TAG_MESSAGE));
    
                convertView.setTag(viewHolder);
    
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
    
            convertView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {               
    
                }
            });
    
            return convertView;
        }
    
        /** ViewHolder Class */
        public class ViewHolder {
            ImageView imgLike = null, imgComments = null,
                    imgShare = null;
            TextView txtId = null,txtDescription = null;
        }
    
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
            case R.id.imgLike:
                strId = ((TextView) view
                        .findViewById(R.id.txtId));
                System.out.println("On Click====="
                        + strId.getText().toString());
    
                urlLike = "http://www.example.com?id="
                        + strId.getText().toString() + "&user_id="
                        + myDetail.getUserId();
    
                new sendLikeData().execute();
    
                break;
            case R.id.imgComments:
    
                break;
            case R.id.imgShare:
    
                break;
            default:
                break;
            }
        }
    
        public class sendLikeData extends AsyncTask<Void, Void, Void> {
            protected void onPreExecute() {
                super.onPreExecute();
            }
    
            @Override
            protected Void doInBackground(Void... arg0) {
                ServiceHandler sh = new ServiceHandler();
                String jsonStr = sh.makeServiceCall(urlLike, ServiceHandler.GET);
                Log.d("Response : Like", ">" + jsonStr);
    
                return null;
            }
    
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
            };
        }
    }
    OutPut is, NullPointer Exception in System.out.println("On Click====="
                            + strId.getText().toString());.
    

    enter image description here

    xml file is,

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/masterLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/five_dp" >
    
        <TextView
            android:id="@+id/txtDescription"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="@dimen/ten_dp"
            android:layout_marginRight="@dimen/ten_dp"
            android:layout_marginTop="@dimen/ten_dp" />
    
        <ImageView
            android:id="@+id/imgImage"
            android:layout_width="fill_parent"
            android:layout_height="150dp"
            android:layout_below="@+id/txtDescription"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="@dimen/ten_dp"
            android:layout_marginLeft="@dimen/ten_dp"
            android:layout_marginRight="@dimen/ten_dp"
            android:layout_marginTop="@dimen/ten_dp"
            android:background="@null"
            android:contentDescription="@string/content_description"
            android:src="@drawable/ic_launcher" />
    
        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/imgImage"
            android:background="@drawable/strip"
            android:baselineAligned="false"
            android:gravity="center_vertical"
            android:orientation="horizontal" >
    
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" >
    
                <ImageView
                    android:id="@+id/imgLike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerInParent="true"
                    android:contentDescription="@string/content_description"
                    android:src="@drawable/like" />
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignTop="@+id/imgLike"
                    android:layout_toRightOf="@+id/imgLike"
                    android:background="@drawable/getbg"
                    android:gravity="center"
                    android:padding="@dimen/two_dp"
                    android:textColor="@color/white"
                    android:textSize="@dimen/ten_sp" />
            </RelativeLayout>
    
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" >
    
                <ImageView
                    android:id="@+id/imgComments"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerInParent="true"
                    android:contentDescription="@string/content_description"
                    android:src="@drawable/comments" />
    
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/imgComments"
                    android:background="@drawable/getbg"
                    android:gravity="center"
                    android:padding="@dimen/two_dp"
                    android:text="+1"
                    android:textColor="@android:color/white"
                    android:textSize="@dimen/ten_sp" />
            </RelativeLayout>
    
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1" >
    
                <ImageView
                    android:id="@+id/imgShare"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerHorizontal="true"
                    android:layout_centerInParent="true"
                    android:contentDescription="@string/content_description"
                    android:src="@drawable/share" />
            </RelativeLayout>
        </LinearLayout>
    
        <TextView
            android:id="@+id/txtId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_margin="@dimen/ten_dp"
            android:text="id"
            android:textSize="20dp" />
    
    </RelativeLayout>
    

    And Logcat is,

    11-24 18:54:20.354: E/AndroidRuntime(7120): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
    11-24 18:54:20.354: E/AndroidRuntime(7120):     Adapter.onClick(Fragment.java:342)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.view.View.performClick(View.java:4562)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.view.View$PerformClick.run(View.java:18918)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Handler.handleCallback(Handler.java:808)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Handler.dispatchMessage(Handler.java:103)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Looper.loop(Looper.java:193)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.app.ActivityThread.main(ActivityThread.java:5388)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at java.lang.reflect.Method.invokeNative(Native Method)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at java.lang.reflect.Method.invoke(Method.java:515)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
    11-24 18:54:20.354: E/AndroidRuntime(7120):     at dalvik.system.NativeStart.main(Native Method)