如何在Android中的可扩展RecyclerView上设置onClickListner

时间:2015-10-29 21:27:29

标签: android nullpointerexception android-recyclerview expandablelistadapter

我正在尝试创建一个从本地sqlite数据库获取数据并将它们放入recyclerview的应用程序,下图说明了我要做的事情:enter image description here

除了要点击类别文字链接的部分外,应用程序工作正常,例如饮料,以便它将返回饮料类别中的所有物品,即2 Mazowe物品。只有当您单击带圆圈的 - 或+符号而不是按下文本时,代码才有效。这是代码:

package com.vhg.empire.merchant.Account;

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView; 
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.vhg.empire.merchant.Cart.AddCartItems;
import com.vhg.empire.merchant.R;
import com.vhg.empire.merchant.database.ProductDetailObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by VinceGee on 09/30/15.
 */
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;

private List<Item> data;

public ExpandableListAdapter(List<Item> data) {
    this.data = data;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
    View view = null;
    Context context = parent.getContext();
    float dp = context.getResources().getDisplayMetrics().density;
    int subItemPaddingLeft = (int) (18 * dp);
    int subItemPaddingTopAndBottom = (int) (5 * dp);
    switch (type) {
        case HEADER:
            LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.expandable_list_header, parent, false);
            ListHeaderViewHolder header = new ListHeaderViewHolder(view);
            return header;
        case CHILD:
            TextView itemTextView = new TextView(context);
            itemTextView.setPadding(subItemPaddingLeft, subItemPaddingTopAndBottom, 0, subItemPaddingTopAndBottom);
            itemTextView.setTextColor(0x88000000);
            itemTextView.setLayoutParams(
                    new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.WRAP_CONTENT));
            return new RecyclerView.ViewHolder(itemTextView) {
            };
    }
    return null;
}

public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    final Item item = data.get(position);
    switch (item.type) {
        case HEADER:
            final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
            itemController.refferalItem = item;
            itemController.header_title.setText(item.text);
            if (item.invisibleChildren == null) {
                itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
            } else {
                itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
            }
            itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.invisibleChildren == null) {
                        item.invisibleChildren = new ArrayList<Item>();
                        int count = 0;
                        int pos = data.indexOf(itemController.refferalItem);
                        while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
                            item.invisibleChildren.add(data.remove(pos + 1));
                            count++;
                        }
                        notifyItemRangeRemoved(pos + 1, count);
                        itemController.btn_expand_toggle.setImageResource(R.drawable.circle_plus);
                    } else {
                        int pos = data.indexOf(itemController.refferalItem);
                        int index = pos + 1;
                        for (Item i : item.invisibleChildren) {
                            data.add(index, i);
                            index++;
                        }
                        notifyItemRangeInserted(pos + 1, index - pos - 1);
                        itemController.btn_expand_toggle.setImageResource(R.drawable.circle_minus);
                        item.invisibleChildren = null;
                    }
                }
            });
            break;
        case CHILD:
            TextView itemTextView = (TextView) holder.itemView;
            itemTextView.setText(data.get(position).text);
            break;
    }
    final Item model = data.get(position);
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(final View v) {
            LinearLayout layout = new LinearLayout(v.getContext());
            layout.setOrientation(LinearLayout.VERTICAL);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            layoutParams.setMargins(30, 20, 30, 0);

            // Set up the input_desc
            final EditText input_desc = new EditText(v.getContext());
            final EditText input_qty = new EditText(v.getContext());

            // Specify the type of input_desc expected; this, for example, sets the input_desc as a password, and will mask the text
            input_desc.setInputType(InputType.TYPE_CLASS_TEXT);
            input_desc.setHint(R.string.input_hint);

            input_qty.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
            input_qty.setHint(R.string.input_qty);


            layout.addView(input_desc, layoutParams);
            layout.addView(input_qty, layoutParams);

            try {
                if (!model.getProductDetailObject().getP_name().equals(null)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
                    builder.setMessage(model.getProductDetailObject().getP_name())
                            .setView(layout)
                            .setPositiveButton(R.string.submit, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // FIRE ZE MISSILES!
                                    String m_Text_input_desc = input_desc.getText().toString();
                                    String qnty_int_string = input_qty.getText().toString();

                                    int m_Text_input_qty = 0;

                                    if (qnty_int_string != null &&  !qnty_int_string.trim().isEmpty()  ) {
                                        m_Text_input_qty = Integer.parseInt(qnty_int_string);
                                    }



                                    if (!getValidation(m_Text_input_desc, m_Text_input_qty, input_desc)) {
                                        Toast.makeText(v.getContext(), "Enter valid desc",
                                                Toast.LENGTH_SHORT).show();

                                        return;
                                    }


                                    new AddCartItems().setCartItems(model.getProductDetailObject().getP_name(),
                                            m_Text_input_desc, m_Text_input_qty, false);

                                    Toast.makeText(v.getContext(), "Desc : " + m_Text_input_desc + " Quanity : " + m_Text_input_qty,
                                            Toast.LENGTH_SHORT).show();

                                }
                            })
                            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });

                    //do something
                    builder.show();
                }
            } catch (NullPointerException e) {
                Toast.makeText(v.getContext(), "Select Product", Toast.LENGTH_SHORT).show();

            }


        }
    });
}

private boolean getValidation(String input_name, int input_qnty, EditText input_desc) {
    boolean valid = true;

    if (input_name.isEmpty() || input_name.length() < 3) {
        input_desc.setError("at least 3 characters");
        valid = false;
    } else {
        input_desc.setError(null);
    }
    return valid;
}

@Override
public int getItemViewType(int position) {
    return data.get(position).type;
}

@Override
public int getItemCount() {
    return data.size();
}

private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
    public TextView header_title;
    public ImageView btn_expand_toggle;
    public Item refferalItem;

    public ListHeaderViewHolder(View itemView) {
        super(itemView);
        header_title = (TextView) itemView.findViewById(R.id.header_title);
        btn_expand_toggle = (ImageView) itemView.findViewById(R.id.btn_expand_toggle);
    }
}

public static class Item {
    public int type;
    public String text;
    public List<Item> invisibleChildren;
    private ProductDetailObject mText;

    public Item() {
    }

    public Item(int type, String text, ProductDetailObject txt) {
        this.type = type;
        this.text = text;
        this.mText = txt;

    }

    public ProductDetailObject getProductDetailObject() {

        return mText;
    }
}
}

目前我已经创建了一个try-catch块来满足单击文本时生成的Null指针。 Null-Pointer由toast“选择产品”捕获。请帮助使文本和带圆圈的符号填充子元素。

这是堆栈跟踪:

10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant D/AndroidRuntime: Shutting down VM
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime: FATAL EXCEPTION: main
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime: Process: com.vhg.empire.merchant, PID: 9303
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at com.vhg.empire.merchant.Account.ExpandableListAdapter$3.onClick(ExpandableListAdapter.java:138)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.view.View.performClick(View.java:4780)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:19866)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:739)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:95)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5257)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-30 13:52:19.580 9303-9303/com.vhg.empire.merchant E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

ExpandandableListAdapter.java是上面的那一行,第138行是以下行:if(!model.getProductDetailObject()。getP_name()。equals(null)){

0 个答案:

没有答案