Search code examples
android-intentandroid-studioandroid-listviewandroid-volleybaseadapter

Application crashing when writing button click event on listview in android studio


I have tried all the tricks provided by almost all sites.When i add the onClickListener to the button or any other control in the getview of the adapter, the application crashes. When i delete the code for on click, the application deosnt crash. But i need to write click events on the button in the listview. Any kind of advice will be appreciated!

This is my code for the ListView adapter.

    public class CustomListAdapter extends BaseAdapter{

    private Activity activity;
    private LayoutInflater inflater;
    private List<ProductDetails> productDetailsList;
   // Context context;
    int prodId;
    String prodName, prodPrice, prodImgUrl, prodDescription;
    ImageLoader imageLoader = VolleySingleton.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<ProductDetails> productDetailsList){
        this.activity = activity;
        this.productDetailsList = productDetailsList;
    }

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

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

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

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

        final PlaceHolder holder = new PlaceHolder();

        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        Log.d("Inflater", "checked inflater null");

        if (convertView == null){
            Log.d("convertView ", "checked convertView null");
            convertView = inflater.inflate(R.layout.single_product_list,null);
            Log.d("convertView assigned ", "placed the inflater to convertView ");
        }

        if (imageLoader == null)
            imageLoader = VolleySingleton.getInstance().getImageLoader();

        Log.d("Image Loader", "checked Image loader null");
        holder.imgProduct = (NetworkImageView) convertView.findViewById(R.id.network_prod_img);
        Log.d("Image View", "checked referred image view");
        holder.nameProduct = (TextView) convertView.findViewById(R.id.prod_name);
        Log.d("nameProduct text View", "checked referred nameProduct view");
        holder.priceProduct = (TextView) convertView.findViewById(R.id.prod_price);
        Log.d("priceProduct text View", "checked referred priceProduct view");
        holder.addToCart = (Button)convertView.findViewById(R.id.add_cart_btn);
        Log.d("priceProduct Button", "checked referred Add to cart button");

        //get the product data for the row
        ProductDetails pd = productDetailsList.get(position);
        Log.d("PRODUCT DATA", "got product data for the row");

        //set the product image to the layout
        holder.imgProduct.setImageUrl(pd.getProductImgUrl(), imageLoader);
        Log.d("SET IMAGE", "set the product image to the layout");
        //set the product name to the layout
        holder.nameProduct.setText(pd.getProductName());
        Log.d("SET NAME", "set the product name to the layout");
        //set the product price to the layout
        holder.priceProduct.setText(String.valueOf(pd.getProductPrice()));
        Log.d("SET PRICE", "set the product price to the layout");

        //when clicking on the product name and image
        holder.nameProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("","");
                Toast.makeText(activity, "clicked on add to cart button", Toast.LENGTH_LONG).show();
            }
        });

        holder.imgProduct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(activity, "clicked on add to cart button", Toast.LENGTH_LONG).show();
            }
        });

        holder.addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(activity, "clicked on add to cart button", Toast.LENGTH_LONG).show();
            }
        });

        return convertView;
    }

    public void gotoProdDetails(int position){

        prodId = productDetailsList.get(position).getProductId();
        prodName = productDetailsList.get(position).getProductName();
        prodPrice = productDetailsList.get(position).getProductPrice();
        prodDescription = productDetailsList.get(position).getProductDesc();
        prodImgUrl = productDetailsList.get(position).getProductImgUrl();

        Intent intent1 = new Intent(activity, ProductDescription.class);

        intent1.putExtra("prodId", prodId);
        intent1.putExtra("prodName",prodName);
        intent1.putExtra("prodPrice",prodPrice);
        intent1.putExtra("prodDescription",prodDescription);
        intent1.putExtra("prodImgUrl", prodImgUrl);

        activity.startActivity(intent1);
    }

    class PlaceHolder{

        NetworkImageView imgProduct;
        TextView nameProduct;
        TextView priceProduct;
        Button addToCart;
    }

LogCat is as follows

    11-04 04:25:39.105 1210-1261/system_process W/AudioService: onLoadSoundEffects(), Error -1 while loading samples
11-04 04:25:39.115 897-897/com.example.android.shoppingcart D/onItemClick id: 7
11-04 04:25:39.325 897-897/com.example.android.shoppingcart W/EGL_emulation: eglSurfaceAttrib not implemented
11-04 04:25:39.355 897-897/com.example.android.shoppingcart W/EGL_emulation: eglSurfaceAttrib not implemented
11-04 04:25:39.415 897-897/com.example.android.shoppingcart D/ProductList: [{"id":"7","id_prod":"5","description_prod":"chip","image_url":"http:\/\/192.168.1.8\/shopping_cart\/images\/products\/5.jpg","price_prod":"2.98","name_prod":"Ele1"},{"id":"7","id_prod":"6","description_prod":"Laptops","image_url":"http:\/\/192.168.1.8\/shopping_cart\/images\/products\/6.jpg","price_prod":"24259","name_prod":"Ele2"},{"id":"7","id_prod":"7","description_prod":"Chip Board","image_url":"http:\/\/192.168.1.8\/shopping_cart\/images\/products\/7.jpg","price_prod":"122.98","name_prod":"Ele3"}]
11-04 04:25:39.415 897-897/com.example.android.shoppingcart D/convertView: checked convertView null
11-04 04:25:39.415 897-897/com.example.android.shoppingcart I/dalvikvm-heap: Grow heap (frag case) to 4.118MB for 360012-byte allocation
11-04 04:25:39.435 897-897/com.example.android.shoppingcart I/dalvikvm-heap: Grow heap (frag case) to 4.888MB for 810012-byte allocation
11-04 04:25:39.445 897-897/com.example.android.shoppingcart D/convertView assigned: placed the inflater to convertView 
11-04 04:25:39.445 897-897/com.example.android.shoppingcart D/priceProduct Button: checked referred Add to cart button
11-04 04:25:39.445 897-897/com.example.android.shoppingcart W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xb37f0678)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime: FATAL EXCEPTION: main
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime: java.lang.NullPointerException
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.ListView.onMeasure(ListView.java:1159)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:124)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:393)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-04 04:25:39.445 897-897/com.example.android.shoppingcart E/AndroidRuntime:     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
11-04 04:25:40.155 1374-1374/com.android.launcher W/EGL_emulation: eglSurfaceAttrib not implemented

activity_products_list.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.android.shoppingcart.ProductList">

   <ListView
       android:id="@+id/prod_list"
       android:layout_width="match_parent"
       android:background="@android:color/transparent"
       android:cacheColorHint="@android:color/transparent"
       android:layout_height="wrap_content">

   </ListView>

</LinearLayout>

single_product_list.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/single_product_row"
    android:padding="15dp">

    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/network_prod_img"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:src="@drawable/small_default"
        android:scaleType="centerCrop"
        android:layout_marginRight="20dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/prod_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/def_prod_name"
        android:textSize="17sp"
        android:padding="5dp"
        android:layout_alignTop="@+id/network_prod_img"
        android:layout_toEndOf="@+id/network_prod_img"
        android:layout_alignParentEnd="true" />

    <TextView
        android:id="@+id/prod_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/price_val"
        android:layout_below="@+id/prod_name"
        android:padding="5dp"
        android:textSize="15sp"
        android:layout_toEndOf="@+id/network_prod_img"
         />

    <Button
        android:id="@+id/btn_add_cart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/add"
        android:padding="12dp"
        android:layout_below="@id/prod_price"
        android:layout_toEndOf="@id/network_prod_img"
        android:background="#E57373"
        />

</RelativeLayout>

Solution

  • Thanks for all the answers...They helped me a lot to research more! At last I got the solution.

    In order to make the button clickable and also the listview clickable, I wrote 2 different click events as shown below :

    in the MainActivity.java outside the onCreate():

     public void addToCart(View view) {
        Button bt = (Button) view;
    
    /*To get the position of the corresponding row clicked*/
        View parentRow = (View) view.getParent();
        ListView listView = (ListView) parentRow.getParent();
        final int position = listView.getPositionForView(parentRow);
        Toast.makeText(this, productDetailsList.get(position).getProductName() + " added to cart", Toast.LENGTH_LONG).show();
    }
    

    Inside the OnCreate():

     listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(context, "An item of the ListView is clicked.", Toast.LENGTH_LONG).show();
                prodId = productDetailsList.get(position).getProductId();
                prodName = productDetailsList.get(position).getProductName();
                prodPrice = productDetailsList.get(position).getProductPrice();
                prodDescription = productDetailsList.get(position).getProductDesc();
                prodImgUrl = productDetailsList.get(position).getProductImgUrl();
    
                Intent intent1 = new Intent(getApplicationContext(), ProductDescription.class);
    
                intent1.putExtra("prodId", prodId);
                intent1.putExtra("prodName", prodName);
                intent1.putExtra("prodPrice", prodPrice);
                intent1.putExtra("prodDescription", prodDescription);
                intent1.putExtra("prodImgUrl", prodImgUrl);
    
                startActivity(intent1);
            }
        });