toggle button state of 2 buttons within listview row

79 Views Asked by At

i have an activity that shows a listview with 2 rows. Each row has a question, which is pulled from the DB and 2 buttons on ech row, A YES button and a NO button.

I am trying to set the pressed state of the user's choice on each button per row. so if the user hits the light green YES button, then it turns darker green to indicate selected and the red NO button should be unselected.

What is happening is if i hit the YES button on row one, the state of the YES button on row 2 changes instead.

I've placed a structure in the class to hold the states but it is not working correctly. Has anyone any ideas as to why this is not working correctly?

public class CarerRetentionQuestionsActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{


    private static final String TAG = CarerRetentionQuestionsActivity.class.getSimpleName();
    NfcScannerApplication appObj;
    Cursor cursor;
    ListView listViewQuestions;

    MyAdapter myAdapter;

    LoaderManager loadermanager;
    CursorLoader cursorLoader;

    Context context;

    Cursor c;

    Button buttonYes;
    Button buttonNo;

    Button submit;

    private boolean[][] buttonStates;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_carer_retention);

        loadermanager = LoaderManager.getInstance(this);
        appObj = (NfcScannerApplication) getApplication();

        context = this;

        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.drawable.beeactionbar);
        setTitle("Carer Wellbeing");


        listViewQuestions = (ListView) findViewById(R.id.listviewcarerretention);





        submit = (Button) findViewById(R.id.buttoncarerwellbeingsubmit);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "submit clicked");

                String res2 = appObj.loginValidate.haveCarerRetentionQuestionsBeenAsked();

                if (res2 != null && res2.equalsIgnoreCase("YES")) {

                    Intent i = new Intent(CarerRetentionQuestionsActivity.this, NfcscannerActivity2.class);
                    i.setAction("QRCODE_ACTION");
                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(i);

                }


            }
        });







        Cursor anyquestionsInDB = appObj.loginValidate.queryAllFromCarerRetentionQuestions();

        if(anyquestionsInDB != null && anyquestionsInDB.getCount() == 0) {


            ContentValues cv = new ContentValues();
            cv.putNull(LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME);
            cv.put(LoginValidate.C_CARERRETENTIONQUESTIONTIME_QUESTION, "Do you feel supported in your role?");
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_TIMESTAMP);
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_ANSWER);
            cv.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_SENTTOSERVER);

            appObj.loginValidate.insertCarerRetentionQuestions(cv);

            ContentValues cv2 = new ContentValues();
            cv2.putNull(LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME);
            cv2.put(LoginValidate.C_CARERRETENTIONQUESTIONTIME_QUESTION, "Are you happy with the number of hours we are asking you to deliver?");
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_TIMESTAMP);
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_ANSWER);
            cv2.putNull(LoginValidate.C_CARERRETENTIONQUESTIONTIME_SENTTOSERVER);

            appObj.loginValidate.insertCarerRetentionQuestions(cv2);

        }

        try{
            anyquestionsInDB.close();
        }catch(Exception e){}




        String[] from = { C_CARERRETENTIONQUESTIONTIME_QUESTION};
        int[] to = { R.id.rowcarerretentionquestion};

        myAdapter = new MyAdapter(appObj, R.layout.rowcarerretention, null, from, to, 0);
        listViewQuestions.setAdapter(myAdapter);

        loadermanager.initLoader(1, null, this);


    }//END OF onCreate



    private class MyAdapter extends SimpleCursorAdapter {



        public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags) {
            super(context, layout, c, from, to, flags);

            buttonStates = new boolean[getCount()][2]; // Initialize button states array based on the count of items in the list
            // Initially set all buttons to not selected
            for (int i = 0; i < getCount(); i++) {
                buttonStates[i][0] = false; // Yes button
                buttonStates[i][1] = false; // No button
            }


        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Log.e(TAG, "inside myadapter getview");
            View v = super.getView(position, convertView, parent);
            if(v == null)
                return null;

            c = (Cursor)getItem(position);




            final String question = c.getString(c.getColumnIndexOrThrow(C_CARERRETENTIONQUESTIONTIME_QUESTION));
            ((TextView)v.findViewById(R.id.rowcarerretentionquestion)).setText( question);

            Log.e(TAG, "question is set, about to inflate yes/no buttons");

            buttonYes = (Button) v.findViewById(R.id.rowcarerretentionbuttonyes);
            buttonNo = (Button) v.findViewById(R.id.rowcarerretentionbuttonno);



            buttonYes.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e(TAG, "button yes clicked");

                    // Toggle the state of the Yes button
                    buttonStates[position][0] = !buttonStates[position][0];
                    // Set the No button state to not selected
                    buttonStates[position][1] = false;
                    // Update the visual appearance of buttons
                    updateButtonState(position);

                    //----------------

                    buttonYes.setSelected(true);
                    buttonNo.setSelected(false);

                    DateTime dt = new DateTime();
                    long dtmills2 = dt.getMillis();

                    appObj.loginValidate.updateCarerRetentionQuestionsAsBeenAsked(question, "YES", dtmills2);



                }
            });


            buttonNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.e(TAG, "button no clicked");

                    // Toggle the state of the No button
                    buttonStates[position][1] = !buttonStates[position][1];
                    // Set the Yes button state to not selected
                    buttonStates[position][0] = false;
                    // Update the visual appearance of buttons
                    updateButtonState(position);

                    //-------------------------

                    buttonYes.setSelected(false);
                    buttonNo.setSelected(true);

                    DateTime dt2 = new DateTime();
                    long dtmills2 = dt2.getMillis();

                    appObj.loginValidate.updateCarerRetentionQuestionsAsBeenAsked(question, "NO", dtmills2);



                }
            });


            // Update the visual appearance of buttons based on their states
            updateButtonState(position);

            return v;
        }
            }



    // Method to update the visual appearance of buttons based on their states
    private void updateButtonState(int position) {
        // Get the current view from ListView
        View view = listViewQuestions.getChildAt(position - listViewQuestions.getFirstVisiblePosition());
        if (view != null) {
            // Find the Yes and No buttons within the current view
            Button buttonYes = view.findViewById(R.id.rowcarerretentionbuttonyes);
            Button buttonNo = view.findViewById(R.id.rowcarerretentionbuttonno);

            // Update Yes button state
            if (buttonStates[position][0]) {
                // Set selected state appearance
                buttonYes.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green1));
            } else {
                // Set not selected state appearance
                buttonYes.setBackgroundColor(ContextCompat.getColor(mContext, R.color.green4));
            }

            // Update No button state
            if (buttonStates[position][1]) {
                // Set selected state appearance
                buttonNo.setBackgroundColor(ContextCompat.getColor(mContext, R.color.red1));
            } else {
                // Set not selected state appearance
                buttonNo.setBackgroundColor(ContextCompat.getColor(mContext, R.color.red4));
            }
        }
    }




    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {


        String[] projection = { LoginValidate.C_ID_CARERRETENTIONQUESTIONTIME, C_CARERRETENTIONQUESTIONTIME_QUESTION};


        cursorLoader = new CursorLoader(this, RR3ContentProvider.CONTENT_URI_CARERRETENTION, projection, null, null, null);
        return cursorLoader;
    }


    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {

        if(myAdapter!=null && c !=null)
            myAdapter.swapCursor(c); //swap the new cursor in.
        else
            Log.e(TAG,"OnLoadFinished: mAdapter is null");
    }


    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {

        if(myAdapter!=null)
            myAdapter.swapCursor(null);
        else
            Log.e(TAG,"OnLoadFinished: mAdapter is null");

    }





}//end of class
0

There are 0 best solutions below