在跨活动的SharedPreferences中存储值

时间:2015-03-16 06:18:24

标签: java android sharedpreferences

我是Android的新手,并且有一个任务是开发一个小项目在我的大学提交,我已经尽了最大努力,但现在我需要一些帮助

我先告诉你,what i am trying to do ?

我有两项活动,MainActivityAccountActivity

MainActivity我使用button 切换AccountActivity

AccountActivity我尝试在SharedPreference中存储strBalance值,但每当我点击back按钮,然后再次来AccountActivity总是获得"1000"不是我存储在SharedPreference中的那个值。

以下是AccountActivity.java的完整代码: -

public class AccountActivity extends Activity {

    EditText editAmount;
    int strAmount;
    Button btnPayment;
    TextView textBalance;
    int strBalance; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_account);      

        editAmount = (EditText) findViewById(R.id.editAmt);
        btnPayment = (Button) findViewById(R.id.btnPay);
        textBalance = (TextView) findViewById(R.id.textBalance);

        strBalance = 1000;

        textBalance.setText("Your current balance is: $ "+strBalance);      

        btnPayment.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub              
                SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);  
                Editor editor = pref.edit();

                strAmount = Integer.parseInt(editAmount.getText().toString().trim()); // user input             

                if(strAmount>strBalance) {
                    Toast.makeText(AccountActivity.this, "You don't have enough balance", Toast.LENGTH_SHORT).show();
                }
                else 
                {
                    strBalance = strBalance - strAmount; // 1000 - 500 = 500
                    textBalance.setText("Your current balance is: $ "+strBalance);  
                    Log.v("strBalance", String.valueOf(strBalance)); // 500
                    editor.putInt("key_balance", strBalance);
                    editor.commit();
                }
            }
        });
    }

}

4 个答案:

答案 0 :(得分:0)

- 检查首选项键名是否相同。

答案 1 :(得分:0)

这应该可以正常工作:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
if (pref.getInt("key_balance", 1000) != null) {
    strBalance = pref.getInt("key_balance",1000);
} else {
    strBalance = 1000;
}

而不是

strBalance = 1000;

答案 2 :(得分:0)

这样做,

SharedPreferences sharedPreferences = getSharedPreferences("MyPref", MODE_PRIVATE);
       int any_variable = sharedPreferences.getInt("key_balance", 0);

删除初始化并在onCreate中执行此操作,然后在strBalance时使用新变量。

答案 3 :(得分:0)

您没有从SharedPreferences

检索数据

将您的代码写在onResume()中,如下所示:

@Override
protected void onResume() {
    super.onResume();
    // SharedPreferences retrieval code
}

要详细了解SharedPreferences,请查看此link