Search code examples
androidsharedpreferencesoncreatetogglebutton

Force close with SharedPreferences and toggle button in android


i have a problem with my toggle button and i get always a force close. The code of button:

public void getToggle(View view) {
        boolean on = ((ToggleButton) view).isChecked();
        if (on) {
            PackageManager pm = getPackageManager();
            ComponentName compName = new ComponentName(getApplicationContext(),
            LowBatteryReceiver.class);
            pm.setComponentEnabledSetting(compName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            PackageManager.DONT_KILL_APP);
            Toast.makeText(MainActivity.this, "Modalità risparmio attivata", Toast.LENGTH_LONG).show();
            TextView textView = (TextView)findViewById(R.id.risparmiostate);
            textView.setText("Modalità risparmio on");

            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tgpref", true); // value to store
            editor.commit();

        }else{
            PackageManager pm = getPackageManager();
            ComponentName compName = new ComponentName(getApplicationContext(),
            LowBatteryReceiver.class);
            pm.setComponentEnabledSetting(compName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
            Toast.makeText(MainActivity.this, "Modalità risparmio disattivata", Toast.LENGTH_LONG).show();
            TextView textView = (TextView)findViewById(R.id.risparmiostate);
            textView.setText("Modalità risparmio off");

            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tgpref", false); // value to store
            editor.commit();
        }
    }

and in the onCrerate

public SharedPreferences preferences;
    /** Called when the activity is first created. */
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
        boolean tgpref = preferences.getBoolean("tgpref", true);  //default is true
        if (tgpref = true) //if (tgpref) may be enough, not sure
        {
          togglebutton.setChecked(true);
        }
        else
        {
            togglebutton.setChecked(false);
        }

Any ideas? I tryied everything. Thanks. My logcat doesn't work (i don't know why). Doesn't show me anything.


Solution

  • Change

    SharedPreferences preferences = getPreferences(MODE_PRIVATE); 
    

    to

     preferences = getPreferences(MODE_PRIVATE);
    

    in onCreate of Activity because you are not initializing preferences instance which u have declared as class level field before using it in getToggle method