实现SharedPreferences

实现SharedPreferences

这是我的代码。
 我有一个文本视图和2个按钮接受和拒绝。当用户单击接受按钮时,我使用共享的首选项将状态保存为100。

下次用户登录时,我需要检查用户是否已经单击了接受按钮。
 如果他已经接受了,那我应该去家庭活动。

用户单击接受后,就不需要再次显示此活动。

public int kill;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Toast.makeText(Eula.this, "Status of the app is "+kill, Toast.LENGTH_LONG).show();
    if(kill==100)
    {
    Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setComponent(new ComponentName("mobi.infoways.triviavs1_0","mobi.infoways.triviavs1_0.Home"));
        startActivity(intent);
    }
    setContentView(R.layout.eulatxt);
    Intent i2 = getIntent();
    addListenerOnButton();
}
        private void addListenerOnButton() {

        TextView t = (TextView) findViewById(R.id.txtv1);
        t.setText(f);
        Button Accept = (Button) findViewById(R.id.btn1);
            Accept.setOnClickListener(startListener);
            Button Reject = (Button) findViewById(R.id.btn2);
            Reject.setOnClickListener(startListener);
}

        OnClickListener startListener = new OnClickListener()
        {
            public void onClick(View v) {

          switch (v.getId()) {
             case R.id.btn1:

                 SharedPreferences prefs = getPreferences(MODE_PRIVATE);
                 SharedPreferences.Editor editor = prefs.edit();
                 editor.putInt("storedInt",100);
                 editor.commit();
                     kill = prefs.getInt("storedInt", 100);
                    Toast.makeText(Eula.this, "status =" + kill, Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.setComponent(new ComponentName("mobi.infoways.triviavs1_0","mobi.infoways.triviavs1_0.Home"));
                startActivity(intent);
              break;
             case R.id.btn2:
                 Toast.makeText(Eula.this, "button 2 clicked", Toast.LENGTH_SHORT).show();
          Eula.this.finish();
              break;
          }

    };

}

最佳答案

参考下面的代码

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Boolean checkforFirstTime;

sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(getApplicationContext());
editor = sharedPreferences.edit();

checkforFirstTime = sharedPreferences.getBoolean("checkforFirstTime", true);

//Checking whether application is launched first time
if (checkforFirstTime) {

    //your code
    editor.putBoolean("checkforFirstTime", false);
    editor.commit();

 } else {

 }

关于android - 实现SharedPreferences,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11734628/

10-13 04:56