如果玩家第一次赢得该级别,我想要做的就是添加5个'硬币'。 这就是我所拥有的。它在
之下 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_winroundactivity);
**initialize();**
}
private void initialize(){
SharedPreferences coin = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newcoin = coin.getString("coin","");
Double coinnum = 0.0;
try {
coinnum = Double.parseDouble(newcoin);
} catch (NumberFormatException e) {
**coinnum = 0;** // your default value
}
level = getSharedPreferences("level",Activity.MODE_PRIVATE);
levelunlock = getSharedPreferences("levelunlock",Activity.MODE_PRIVATE);
if (level.getString("level","").compareTo(levelunlock.getString("levelunlock","")) == 1) {
levelunlock.edit().putString("levelunlock", (level.getString("level", ""))).apply();
if (level.getString("level","").equals("2")){
coin.edit().putString("coin",Double.toString(coinnum) + 5).apply();
textviewcoinnum.setText(newcoin);
}
}
我发布了以下代码。所有归功于@tahsinRupam
答案 0 :(得分:1)
请尝试以下代码:
if (level.getString("level","").equals("2")){
String prevCoin = sharedPreferences.getString("coin", "");
Double newCoin = Double.parseDouble(prevCoin) + 5;
coin.edit().putString("coin", Double.toString(newCoin)).apply();
textviewcoinnum.setText(coin.getString("coin",""));
//supposed to add 5 coins and set set the new value as text in a textView.
}
更新:要检查您是否拥有有效的双倍值,请执行以下操作:
Double coinnum = 0.0;
try {
coinnum = Double.parseDouble(newcoin);
} catch (NumberFormatException e) {
coinnum = 0; // your default value
}
如果您收到NumberFormatException
,请检查您的logcat。希望这会有所帮助。
答案 1 :(得分:0)
这是有效的代码。大部分功劳归功于@tahsinRupam
SharedPreferences coin = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String newcoin = coin.getString("coin","");
double coinnum;
try {
coinnum = Double.parseDouble(newcoin);
}catch (NumberFormatException e) {
coinnum = 0;
}
level = getSharedPreferences("level",Activity.MODE_PRIVATE);
levelunlock = getSharedPreferences("levelunlock",Activity.MODE_PRIVATE);
if (level.getString("level","").compareTo(levelunlock.getString("levelunlock","")) == 1) {
levelunlock.edit().putString("levelunlock", (level.getString("level", ""))).apply();
if (level.getString("level","").equals("2")){
coinnum = coinnum + 5;
coin.edit().putString("coin",(Double.toString((coinnum)))).apply();
newcoin = coin.getString("coin","");
textviewcoinnum.setText(newcoin);
}
}