将值存储在跨活动的 SharedPreference 中

Store Value in SharedPreference across Activities

我是 Android 的新人,在我的大学里接到了一个开发小项目的任务,我已经尽力了,但现在我需要一些帮助

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

我有两个活动,MainActivityAccountActivity

MainActivity 我正在使用 button 切换 AccountActivity

AccountActivity 中,我试图将 strBalance 值存储在 SharedPreference 中,但每当我单击 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();
                }
            }
        });
    }

}

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

这应该可以正常工作:

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;

这样做,

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

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

您没有从 SharedPreferences

检索数据

像这样在 onResume() 中编写代码:

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

要了解有关 SharedPreferences 的更多信息,请查看此 link