简体   繁体   中英

Keyword "this" doesn't work in Listener

I call method, where one of the parameters - context, in OnPreferenceChangeListener. But when i write: "this", i get an error. I tried to write getContext() instead of this, but it's doesn't work too. Tell me, please, what i can do?

public static class MyPreferenceFragment extends PreferenceFragment {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);

        final ListPreference lp = (ListPreference) findPreference("background");
        lp.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {

                String s = String.valueOf(newValue);

                  /*error*/
                    DatabaseHelper.updItem(this, s, "my_appearance", "backgroundPatters", 1);

                return true;
            }
        });
    }
}

Because you are using this inside Preference.OnPreferenceChangeListener and this is a reference to Preference.OnPreferenceChangeListener itself in that scope, not the MyPreferenceFragment . If you want to pass a reference to MyPreferenceFragment then modify your code like this:

DatabaseHelper.updItem(MyPreferenceFragment.this, s, "my_appearance", "backgroundPatters", 1);

You can read more about this here: https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

if DatabaseHelper.updItem requires Context then you can use getActivity() or getContext() to get Context and pass it to DatabaseHelper.updItem .如果DatabaseHelper.updItem需要Context那么您可以使用getActivity()getContext()来获取Context并将其传递给DatabaseHelper.updItemsomething like this:

DatabaseHelper.updItem(getContext(), s, "my_appearance", "backgroundPatters", 1);

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