Search code examples
androidpreferenceactivity

Cannot refer to a non-final variable inside an inner class. How do I implement onPreferenceClickListener?


While I realize that this question has been asked once or twice ago but I still don't have a clue how I am supposed to fix the problem with creating a listener for each of my checkboxpreferences.

Any suggestions as to how I solve this problem?

private void setQueuePreferences(JSONObject[] qInfo) 
{
    PreferenceCategory QueueCategory = (PreferenceCategory)findPreference("category_queues");
    CheckBoxPreference[] cbox_queues = new CheckBoxPreference[qInfo.length];

    for(int i = 0; i < qInfo.length; i++)
    {
        cbox_queues[i] = new CheckBoxPreference(this);
        cbox_queues[i].setKey("queue_" + i);

        // Formatting the queue title
        String name = qInfo[i].optString("name").replace("-", " ");
        cbox_queues[i].setTitle(name);

        if(qInfo[i].optString("active").contentEquals("1"))
            cbox_queues[i].setChecked(true);
        else
            cbox_queues[i].setChecked(false);

        QueueCategory.addPreference(cbox_queues[i]);
        cbox_queues[i].setOnPreferenceClickListener(new OnPreferenceClickListener()
        {

            public boolean onPreferenceClick(Preference preference) 
            {
                final String[] param = new String[1];
                param[0] = qInfo[i].optString("name");

                if(cbox_queues[i].isChecked())
                {   
                    new JoinQueueTask().execute(param);
                }
                else
                    new LeaveQueueTask().execute(param);
            }

        });
    }
}

Solution

  • You can mark an array as final and still change the elements inside it. You can't however assign a different array to that variable.

    As for the i variable, you can just create a new final int inside the loop like this:

    final int ii = i;
    

    and use that one instead.