Issue
I'm making a simple app that has a button. When a pokemon is caught, I want the text to be "release" and when it's not, to be "catch!". When clicking the button, I want to change caught from true to false or vice-versa.
For now, i've done this (it doesn't work as I expected):
public void toggleCatch(View view) {
boolean caught;
String name = nameTextView.getText().toString();
SharedPreferences captured = getSharedPreferences("pokemon_name",Context.MODE_PRIVATE);
if (captured.contains (name) ){
catch_button.setText("Release");
caught=true;
}
else{
catch_button.setText("Catch!");
caught=false;
}
if (caught) {
getPreferences(Context.MODE_PRIVATE).edit().putString("pokemon_name", name).commit();
} else {
getPreferences(Context.MODE_PRIVATE).edit().remove(name).commit();
}
}
I would be very thankful if someone can help me!
I'm lost so I don't know if I'm on the correct path, my code is probably completely wrong.
Solution
I guess here is what you want:
In your app, you have an EditText
that allows users to input pokemon name. When users click on the toggle catch button,
If the pokemon name is captured (the pokemon name has been saved in the
SharePreferences
), then remove the pokemon name from theSharePreferences
and set the text of the button to "Release".If the pokemon name is not captured (the pokemon name hasn't been saved in the
SharePreferences
), then add the pokemon name to theSharePreferences
and set the text of the button to "Catch!".
Solution
public void toggleCatch(View view) {
String name = nameTextView.getText().toString().trim();
SharedPreferences captured = getSharedPreferences("pokemon_name", Context.MODE_PRIVATE);
boolean caught = captured.contains(name);
if (caught) {
captured.edit().remove(name).apply();
catch_button.setText("Release");
} else {
captured.edit().putBoolean(name, true).apply();
catch_button.setText("Catch!");
}
}
Answered By - Son Truong
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.