我正在寻求帮助。在我的一个活动中,我有变量id_wallet,我想将值保存在SharedPreferences中并用于其他活动。怎么做?代码简介。我在其他类中使用变量wallet_id。
public class ChooseWallet extends AppCompatActivity {
public static int wallet_id;
listViewChooseWallet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
wallet_id= (position+1);
SaveInt("key",wallet_id);
Toast.makeText(getApplicationContext(), "Wallet number "+(position+1)+" active!", Toast.LENGTH_SHORT).show();
}
});
public void SaveInt(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadInt(Context mContext){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
walllet_id = sharedPreferences.getInt("key", 1);
}
其他活动(简称):
public class AddOut extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_out);
addoutbalnce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Double.parseDouble(amount.getText().toString()) > 0 && ChooseWallet.wallet_id != 0 && amount.getText().toString() != null) {
double amount = Double.parseDouble(amount.getText().toString());
amount= (-amount);
String coment = commentout.getText().toString();
ChooseWallet wb = new ChooseWallet();
wb.LoadInt(getApplicationContext());
db.UpdateAmount(ChooseWallet.wallet_id,amount);
db.AddTransaction(ChooseWallet.wallet_id, amount, coment, id_cat, date);
Toast.makeText(getApplicationContext(), "Add", Toast.LENGTH_SHORT).show();
}
else if(Double.parseDouble(amount.getText().toString()) < 0 || amount.getText().toString() == null){
amount.setError("Error!");
}
}
});
答案 0 :(得分:0)
可能您的模拟器不保存共享偏好。尝试使用手机启动应用。