在android studio

时间:2015-11-04 09:23:05

标签: android-intent android-studio android-listview android-volley baseadapter

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

这是我的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>

3 个答案:

答案 0 :(得分:0)

似乎有两种方法让按钮工作:(我喜欢第二个更多,更少的文字)

1)Java:OnClickHandlers:

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

2)按钮解析中的XML:android:onClick="your_method_that_does_something"

我没有看到你在做什么,正在创建按钮。然后将按钮连接到UI中的某个内容。然后附上一个听众。

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

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

<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代码中。

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

答案 1 :(得分:0)

显示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 :(得分:0)

感谢所有答案......他们帮助我做了很多研究!最后我得到了解决方案。

为了使按钮可点击并且listview可点击,我写了两个不同的点击事件,如下所示:

在onCreate()之外的MainActivity.java中:

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