简体   繁体   中英

Android :-Switch button in RecyclerView.Adapter OnCheckChangeListener

1)I am Using Switch button in Recycler View Adapter .

2)Problem is "Context" i want to show Toast when Switch button is checked or unChecked.

3) which Context i should use in Toast to show the toast.

I want to show toast when switch OnCheckChangeListener

public class ChannelPartenerMyBuddiesAdapter extends RecyclerView.Adapter<ChannelPartenerMyBuddiesAdapter.MyViewHolder> {


    // String ChannelPartenerURL = Ipaddress.ChannelPartener();
    String Ip = Ipaddress.ipaddress();
    String ChannelPartenerURL = Ip + "ChannelPartener.php/";
    String TAG = Utils.LogcatTag;

    String CBId, CBActive;
    ChannelPartenerMyBuddies channelPartenerMyBuddies = new ChannelPartenerMyBuddies();
    private List<ChannelPartenerMyBuddiesItom> channelPartenerMyBuddiesItomsList;
    private ChannelPartenerMyBuddiesAdapter thisAdapter = this;
    View view;

    Context context;
    Activity activity;


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView inputMyCashBuddyID, inputMyCashBuddyName, inputMyCashBuddyMobile, inputMyCashBuddyLocation;
        ImageView inputCashBudyprofilPic;
        Button buttonEdit, buttonDelete;
        Switch mySwitch;

        public MyViewHolder(View view) {
            super(view);
            inputMyCashBuddyID = (TextView) view.findViewById(R.id.mtextMyBuddiesID);
            inputMyCashBuddyName = (TextView) view.findViewById(R.id.mtextMyBuddiesName);
            inputMyCashBuddyMobile = (TextView) view.findViewById(R.id.mtextMyBuddiesMobile);
            inputMyCashBuddyLocation = (TextView) view.findViewById(R.id.mtextMyBuddiesAddress);
            buttonDelete = (Button) view.findViewById(R.id.mbtnMyBuddiesDelete);

            buttonEdit = (Button) view.findViewById(R.id.mbtnMyBuddiesEdit);
            mySwitch = (Switch) view.findViewById(R.id.switch1);

            inputCashBudyprofilPic = (ImageView) view.findViewById(R.id.mCashBuddyProfile);
        }

    }

    public ChannelPartenerMyBuddiesAdapter(List<ChannelPartenerMyBuddiesItom> channelPartenerMyBuddiesItomsList) {
        this.channelPartenerMyBuddiesItomsList = channelPartenerMyBuddiesItomsList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.channel_partener_my_buddies_itom_list, parent, false);

        return new MyViewHolder(itemView);
    }


    @Override
    public void onBindViewHolder(final ChannelPartenerMyBuddiesAdapter.MyViewHolder holder, final int position) {

        final ChannelPartenerMyBuddiesItom channelPartenerMyBuddiesItom = channelPartenerMyBuddiesItomsList.get(position);


        holder.inputMyCashBuddyID.setText(channelPartenerMyBuddiesItom.getMyBuddiesID());
        holder.inputMyCashBuddyName.setText(channelPartenerMyBuddiesItom.getMyBuddiesName());
        holder.inputMyCashBuddyMobile.setText(channelPartenerMyBuddiesItom.getMyBiddiesMobile());
        holder.inputMyCashBuddyLocation.setText(channelPartenerMyBuddiesItom.getMyBuddiesAdress());

        new ImageLoadTask(channelPartenerMyBuddiesItom.getMyBuddiesProfilePic(), holder.inputCashBudyprofilPic).execute();


        String CBstatus = channelPartenerMyBuddiesItom.getMyBuddiesActive();
        if (CBstatus.equals("y")) {
            holder.mySwitch.setChecked(true);
            holder.mySwitch.setText("Active");
        } else {
            holder.mySwitch.setChecked(false);
            holder.mySwitch.setText("DActive");
        }


        holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
                if (bChecked) {
                    Toast.makeText(context, "Checked", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Unchecked", Toast.LENGTH_SHORT).show();

                     }


            }


        });




    }

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

    public void CashBuddyActive(final Context context) {

        Log.e(TAG, ChannelPartenerURL);
        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Updating Cash Buddy ...");
        pDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ChannelPartenerURL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        pDialog.hide();

                        Log.e("Update responce", response);
                        try {

                            JSONObject jsonObject = new JSONObject(response);
                            String Result = jsonObject.getString("code");
                            Log.e("Upadate Cash Buddy Code", Result);
                            if (Result.equals("1")) {
                                Log.e(TAG, "Active Code 1");

                                Intent i = new Intent(thisAdapter.context, ChannelPartenerMyBuddies.class);
                                context.startActivity(i);
                                ((Activity) context).finish();


                            } else {
                                Toast.makeText(context, "Status not Changed", Toast.LENGTH_SHORT).show();
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage());
                pDialog.hide();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getdata", "updateCashBuddyActiveDeactive");
                params.put("insert_CB_ID", CBId);
                params.put("insert_CB_status", CBActive);
                return params;
            }


        };

        //Adding request to request queue
        VolleyAppController.getInstance().addToRequestQueue(stringRequest);

    }

    public void DeleateCashBuddyStatus(final Context context, final String CashBuddyI) {

        Log.e(TAG, ChannelPartenerURL);
        Log.e("Deleat ID", CashBuddyI);
        final ProgressDialog pDialog = new ProgressDialog(context);
        pDialog.setMessage("Updating Cash Buddy ...");
        pDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ChannelPartenerURL,
                new Response.Listener<String>() {

                    @Override
                    public void onResponse(String response) {
                        pDialog.hide();

                        Log.e("Update responce", response);
                        try {

                            JSONObject jsonObject = new JSONObject(response);
                            String Result = jsonObject.getString("code");
                            Log.e("Cash Buddy Code", Result);
                            if (Result.equals("1")) {
                                Intent i = new Intent(thisAdapter.context, ChannelPartenerMyBuddies.class);
                                context.startActivity(i);
                                ((Activity) context).finish();


                            } else {
                                Toast.makeText(context, "Cash Buddy no Deleated", Toast.LENGTH_SHORT).show();
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, error.getMessage());
                pDialog.hide();

            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("getdata", "deleatCashBuddy");
                params.put("insert_CB_ID", CashBuddyI);
                return params;
            }


        };

        //Adding request to request queue
        VolleyAppController.getInstance().addToRequestQueue(stringRequest);

    }

}

I Am getting Below Error in Logcat

Process: com.jmtechnologies.askuscash, PID: 7741
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.Toast.<init>(Toast.java:106)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.Toast.makeText(Toast.java:263)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at com.jmtechnologies.askuscash.ChannelPartener.ChannelPartenerMyBuddiesAdapter$1.onCheckedChanged(ChannelPartenerMyBuddiesAdapter.java:141)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.CompoundButton.setChecked(CompoundButton.java:154)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.Switch.setChecked(Switch.java:862)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.Switch.toggle(Switch.java:857)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.widget.CompoundButton.performClick(CompoundButton.java:118)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.view.View$PerformClick.run(View.java:20262)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:815)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:104)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:194)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5622)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
01-23 15:19:15.188 7741-7741/com.jmtechnologies.askuscash E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

You suppose to pass the context from where you are calling ChannelPartenerMyBuddiesAdapter let's say if you are calling this class from MainActivity then inside your MainActivity write below code

ChannelPartenerMyBuddiesAdapter channelPartenerMyBuddiesAdapter = new ChannelPartenerMyBuddiesAdapter(objectofList<ChannelPartenerMyBuddiesItom>,MainActivity.this);

And in your ChannelPartenerMyBuddiesAdapter class made changes like below

public ChannelPartenerMyBuddiesAdapter(List<ChannelPartenerMyBuddiesItom> channelPartenerMyBuddiesItomsList,Context context) {
    this.channelPartenerMyBuddiesItomsList = channelPartenerMyBuddiesItomsList;
    this.context=context
}

By Adding Below line to set context it also works for me

context = compoundButton.getContext();

below is my updated code To show the Toast

setOnCheckedChangeListener

 holder.mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
                    context = compoundButton.getContext();
                    if (bChecked) {
                        Toast.makeText(context, "Checked", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(context, "Unchecked", Toast.LENGTH_LONG).show();
         }


                }


            });

Here you can add your Context and used that context to show Toast

private Context mContext;
public ChannelPartenerMyBuddiesAdapter(List<ChannelPartenerMyBuddiesItom> channelPartenerMyBuddiesItomsList,Context mContext) {
    this.channelPartenerMyBuddiesItomsList = channelPartenerMyBuddiesItomsList;
    this.mContext=mContext
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM