使用共享首选项保存切换

时间:2014-07-26 10:53:15

标签: android toggle sharedpreferences

我希望允许用户启用或禁用启动画面。

我有一个切换按钮,有两个类: 第一个类,名为 SplashActivity , 处理此类中定义的初始屏幕:

package com.test.splash;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;


public class SplashActivity extends Activity {
/** Called when the activity is first created. */

public SharedPreferences preferences;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences sharedPref = getSharedPreferences("sharedPref1", MODE_PRIVATE);


    boolean sharedPref1 = preferences.getBoolean("sharedPref1", true);
    //???.setChecked(sharedPrefs.getBoolean("NameOfThing  ToSave", true));
    if (sharedPref1 = true) //if (tgpref) may be enough, not sure
    {

MediaPlayer mp = MediaPlayer.create(this, R.raw.play);

mp.start();
    Handler handler = new Handler();
    handler.postDelayed(new Runnable(){
        public void run(){
            finish();
            startActivity(new Intent (SplashActivity.this,asli.class));
        }
    }, 1000);
}
    else
    {
        startActivity(new Intent (SplashActivity.this,asli.class));
    }
    }
}

第二个类名为 asli ,在此课程中我定义了一个共享首选项来保存切换状态。

package com.test.splash;


import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ToggleButton;



public class asli extends PreferenceActivity{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.asli);


    final ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton1);
    toggle.setOnClickListener(new OnClickListener(){
    public void onClick(View v) 
    {
        if (toggle.isChecked()) 
        {
            SharedPreferences.Editor editor = 
getSharedPreferences("sharedPref1", MODE_PRIVATE).edit();
            editor.putBoolean("sharedPref1", true);
            editor.commit();
        }
        else
        {

SharedPreferences.Editor editor =
getSharedPreferences("sharedPref2", MODE_PRIVATE).edit();
            editor.putBoolean("sharedPref2", false);
            editor.commit();
        }
    }

});

}
}

1 个答案:

答案 0 :(得分:0)

问题是您未初始化preferences

您在班级中定义了preferences,但未对其进行初始化。

public SharedPreferences preferences;

你在这行中从null变量得到一个布尔值:

boolean sharedPref1 = preferences.getBoolean("sharedPref1", true);

所以在使用preferences之前,您应该将其初始化为:

preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())