在Android中强制关闭SharedPreferences和切换按钮

时间:2013-07-03 05:28:15

标签: android sharedpreferences oncreate togglebutton

我的切换按钮出现问题,我总是关闭力量。按钮代码:

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();
        }
    }

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);
        }

有什么想法吗?我试了一切。谢谢。我的logcat不起作用(我不知道为什么)。没有给我看任何东西。

2 个答案:

答案 0 :(得分:1)

更改

SharedPreferences preferences = getPreferences(MODE_PRIVATE); 

 preferences = getPreferences(MODE_PRIVATE);

在Activity的onCreate中,因为在getToggle方法

中使用它之前,您没有初始化已声明为类级别字段的首选项实例

答案 1 :(得分:1)

尝试使用

if (tgpref == true)  

if(tgpref)

代替

  

if(tgpref = true)。

尝试在Oncreate()中初始化TextView textView = (TextView)findViewById(R.id.risparmiostate);

同时从SharedPreferences删除SharedPreferences preferences = getPreferences(MODE_PRIVATE);因为您已在全球范围内声明。