2013-09-24 45 views
-1

嘿,我正在尝试做我自己的应用程序,我已经在网上搜索信息,我不明白其他人发现有用的解决方案。但我有一个小问题。我希望应用程序保存布尔值stopValue,当我关闭应用程序时,但是当我尝试此操作时,它不保存值,当我关闭应用程序时,而是将值设置为true。布尔和sharedpreference

我该如何解决这个问题?

感谢您的帮助。

public class Main extends Activity{ 

Button bStart, bStop; 
TextView tvDate, tvKm; 
Spinner spinner1; 
boolean stopValue; 

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

    bStart = (Button) findViewById(R.id.bStart); 
    tvDate = (TextView) findViewById(R.id.tvDate); 
    tvKm = (TextView) findViewById(R.id.tvKm); 
    spinner1 = (Spinner) findViewById(R.id.spinner1); 

    boolean stopValue = false; 
    SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1); 
    stopValue = sp.getBoolean("stop", false); 

    stopValue = getIntent().getBooleanExtra("stop", stopValue); 

    if(stopValue){ 
     bStart.setText("Start"); 
     bStart.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // TODO Auto-generated method stub 
       Intent start = new Intent("com.uniqueapps.runner.START"); 
       startActivity(start); 
      } 
     }); 
    } 
    if(stopValue == false){ 
     bStart.setText("Stop"); 
     bStart.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Intent stop = new Intent("com.uniqueapps.runner.STOP"); 
       startActivity(stop); 
      } 
     }); 
    } 
} 

@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 
} 

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 

    SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1); 
    Editor edit = sp.edit(); 
    edit.putBoolean("stop", true); 
    edit.commit(); 
} 

回答

0

呼叫super.onPause后提交这样的: -

@Override 
protected void onPause() { 
    SharedPreferences sp = getApplicationContext().getSharedPreferences("stopValue", 1); 
    Editor edit = sp.edit(); 
    edit.putBoolean("stop", stopValue); 
    edit.commit(); 
    super.onPause(); 


} 
+0

它的工作原理..谢谢..是因为暂停方法之前调用它保存值? – Niller

+0

是的,当您调用super.onPause()时,框架暂停活动 – Rasmus

1

你在试图保存而不是变量时将真实存在。

+0

我想现在编辑,当我加载应用它不断加载到假..我曾试图改变负载偏好也是一个变量,但这并没有帮助。 – Niller