在 android studio 的列表视图上编写按钮单击事件时应用程序崩溃

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

我已经尝试了几乎所有提供的所有技巧 sites.When 我将 onClickListener 添加到按钮或适配器的 getview 中的任何其他控件,应用程序崩溃。当我删除点击代码时,应用程序不会崩溃。但我需要在列表视图中的按钮上编写点击事件。任何类型的建议将不胜感激!

这是我的 ListView 适配器代码。

    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如下

    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>

似乎有两种方法可以使按钮起作用:(我更喜欢第二种,文字较少)

1) Java: OnClickHandlers:

Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);

2) XML 按钮减量:android:onClick="your_method_that_does_something"

我没看到你在做什么,是创建按钮。然后将按钮连接到 UI 中的一个东西。然后附加一个监听器。

*编辑;你能附上 XML 文件吗?我认为你的问题(也)在那里。

*编辑2;以这种方式更改按钮(向您展示它是如何工作的,并不能解决您所有的问题):

<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"
        android:onClick="toastMe"
        />

并将此方法添加到您的 java 代码中,在主 class.

public void toastMe() {
    Toast.makeText(activity, "Button works", Toast.LENGTH_SHORT).show();
}

java.lang.NullPointerException。 意味着您的声明中有些地方是错误的,这就是为什么它们显示 NULL。

 Button btn_Call ; // declare at the top of the class before oncreate.
 btn_Call = (Button) findViewById(R.id.btn_Call);
 btn_Call.setOnClickListener(new View.OnClickListener() {
         @Override
        public void onClick(View v) {
            // code here
        }
    });

感谢您的所有回答...他们帮助我进行更多研究!终于找到解决方法了

为了使按钮可点击以及列表视图可点击,我编写了 2 个不同的点击事件,如下所示:

在 MainActivity.java 外 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();
}

在 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);
        }
    });