How to change assigned string with method - java

I am trying to write a program where when I use a button a "\" shows, then if I hit that same button a "X" shows, and finally if I hit that same button a third time "(X)" shows. Right now I have this method ......
public void display20closePlayer1(String close) {
TextView playerOneTwentyClose = (TextView) findViewById(R.id.player_one_20_close);
playerOneTwentyClose.setText(String.valueOf(close));
}
that finds the button and sets the text with this....
public void twentyCloseOutPlayer1(View v) {
playerOneClose20 = playerOneClose20 + "\\";
display20closePlayer1 (playerOneClose20);
}
I am storing the string in a public object in my main activity...
String playerOneClose20 = "";
When I run my code and press the button I get a "\" to show up, if I hit it again I get "\" and so on.
Can someone please help to explain a method that would replace the already called "\", with an "X" and then replace the "X" with "(X)" Thanks for the help!

You’re close! The way I would do this is with a global int variable that denotes the stage you’re on (i.e 1 => “/“, so on and so forth)
Then in your on button click listener get the text view and set it depending on the stage number.
Remember to set and reset that int variable otherwise it will mess up your code

Related

Can && be used in if statements?

Im working on an app that converts a currency. I need it so that the user can enter an amount and then select one button which will have a specific material on it and then the user will click another button to convert it to another material. Eg copper converted into silver. But when I run the program for some reason when I click the calculate button nothing happens on the screen and no errors appear. Is it because I'm using && or something else I am very confused as to why it is not working. Here is my code:
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
btCalculate.setText(convert);
}
}
});
}
}
&& means and -- so both buttons have to be pressed at the same time for the if to evaluate to true? Not sure if this is what you intended to do.
When trying to figure out what is going wrong in your code you can use print statements or the debugging option in your IDE to step through your code line by line to see where the problem occurs.
I added a couple print statements to your code to show whether btCopper1 and btSilver2 are pressed and another print statement showing that the btCalculate() method will be called. If nothing prints to the console window at all then you aren't even reaching the onClick() method and something else went wrong before the portion of code that you posted.
btCalculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
System.out.println("btCopper1="+btCopper1.isPressed() + " btSilver2="+btSilver2.isPressed());
int convert = Integer.parseInt(editText.getText().toString());
if (btCopper1.isPressed() && btSilver2.isPressed()){
System.out.println("btCalculate is called");
btCalculate.setText(convert);
}
}
});

Trying to setup a NumberPicker to show value in Toast

I'm using the NumberPicker tool in Android and I changed the value of the integer to String to be able to show it in the Toast I used Integer.toString method but I don't think the problem is that.
The thing is when I tap my button no matter what value I pick in the NumberPicker it shows (0). I'm using the .getValue(); as shown below.
How do I make it get the value that I set on NumberPicker?
numPickerMin = (NumberPicker) findViewById(R.id.numberPickerMinute);
//Min
numPickerMin.setMaxValue(60);
numPickerMin.setMinValue(0);
numPickerMin.setWrapSelectorWheel(false);
int getvalueminute = numPickerMin.getValue();
final String getValMin= Integer.toString(getvalueminute);
silentButton.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
Toast.makeText(MainActivity.this,getValMin,Toast.LENGTH_LONG).show();
}
}
);
You are getting Picker's value after you initialize it so it will always be 0. As I understand your code you want to show correct value in Toast after pressing button? You should move those lines inside OnClickListener:
int getvalueminute = numPickerMin.getValue();
String getValMin= Integer.toString(getvalueminute);

SharedPreferences String Set data lost after app kill (android emulator)

I am running this on an emulator: 5554:Nexus_5_API_22_x86.
I am trying to learn SharedPreferences and have written a simple test program.
It contains two buttons: one adds a String + random # to a set which will be stored in SharedPreferences, and the other prints the contents of that set.
Whenever I press the square button on the bottom right hand of the screen and press 'x' to close the app window, then relaunch the app, the contents of the set are reset - in other words, printing the set yields nothing.
However, if I exit the app using only the back button, the contents remain - in other words, printing the set yields whatever was in it before.
Java:
...
public class MainActivity extends AppCompatActivity
{
final int PREF_MODE_PRIVATE = 0;
TextView output;
Set<String> testSet;
Random randomGenerator = new Random();
SharedPreferences data;
SharedPreferences.Editor dataEditor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output = (TextView) findViewById(R.id.textView); //getting the output textfield
data = getPreferences(PREF_MODE_PRIVATE);
//If first-time setup has not been completed, execute the following block
//I don't want the String Set to be reset to empty every time the app is launched
if(data.getBoolean("initialized", false) == false)
{
//Adding the empty set to storage
testSet = new HashSet<String>();
dataEditor = data.edit();
dataEditor.putStringSet("testSet", testSet); //Add the empty Set to storage
dataEditor.putBoolean("initialized", true); //Set initialized flag to true
dataEditor.apply();
}
}
public void printTestSet(View view)
{
output.setText(""); //Clears the text field
Set<String> toBePrinted = data.getStringSet("testSet", null); //Gets the String Set
//Prints content of the String Set
if(toBePrinted != null)
{
for(String word : toBePrinted)
{
output.append(word + '\n');
}
}
}
public void addToTestSet(View view)
{
//Generate a string followed by a random number and add it to the String Set
int randomInt = randomGenerator.nextInt(1000);
data.getStringSet("testSet", null).add("NEW STRING #" + randomInt);
}
}
The button that prints the String Set calls printTestSet and the one that adds a String to the Set calls addToTestSet.
Upon creation, the app uses a simple boolean to check if it has been initialized the for the first time. If not, it adds an empty String Set to storage and sets the boolean to true. If the boolean is already true (meaning it has already added the empty string set), that step is skipped.
You need to either commit your data either realtime (where you are doing apply) or in application life cycle handler onpause (when your app goes to background). Use option 1 when you have little data or 2 when you have large amount of data to commit.
It looks like you're not saving the shared preferences in addToTestSet.
When you do getStringSet and then add, you need to again save the string Set back into shared prefs like you do in your onCreate() using dataEditor.apply().
Or if you want to be a bit more efficient, you can save your stringSet in the activity's onPause() method to prevent constantly writing to SharedPrefs
When you hit back, your app process isn't being killed, which means when you open it up again the Android system is restoring whatever it can (what was written in textViews, checkboxes that were checked, etc. simple things like that). What you see in the box might not actually be getting populated by SharedPrefs.

Android beginner onClick crash

I'm programming Android for the first time and I'm having some difficulties. The idea is to make a guessing game app in which the user takes a number in his/her head and the app tries to guess it. The user will give hints like higher and lower to the app. For some reason the app crashes after I press the start button. Because of this, I know that there is an error in the onClick method but since it shuts down immediately after I press the start button, I can't use something like a println to debug.
So actually I have 2 questions:
Where does my reasoning fail? (or show me how to figure out my mistakes)
How can I debug things like this?
The start, higher and lower are all buttons in the program.
#Override
public void onClick(View arg0) {
int min = 0;
int max = 100;
Random random = new Random(100);
int answer = 0;
if (arg0 == start) {
answer = random.nextInt(100);
buttonTextView.setText(answer);
}
else if (arg0 == higher){
min = answer;
answer = random.nextInt((max - min) + min);
buttonTextView.setText(answer);
}
else if (arg0 == lower) {
max = answer;
answer = random.nextInt((max-1) - min);
buttonTextView.setText(answer);
}
}
where does my reasoning fail?
You are using the wrong setText() method. In the TextView Docs you will see that there is one which takes an int, this is for retrieving a String resource that you have in your strings.xml so you would pass it a resource id. So your setText() is looking for a resource with the id of whatever your answer variable is. You will want to convert this to a String with something like
buttonTextView.setText(String.valueof(answer));
or one of several different ways.
How can I debug things like this?
When your app crashes there will be an exception in your logcat. This answer can help you to read your logcat. To open your logcat window in Eclipse, if it isn't already, you can do this
Window --> Show View --> Other --> Android --> LogCat
A couple side notes
You should change your params like in onClick() to something meaningful so I would change
public void onClick(View arg0)
to something like
public void onClick(View v) // v for view, could also be view, btn
// whatever makes sense to you and others who may read it
You also should compare the id of your View clicked instead of the View itself. So you would compare it with something like the following (assuming you changed arg0 to v)
if (v.getId() == R.id.start) // Assuming start is the id in your xml of your Button
// this will also allow you to use a switch statement
Your variables in onClick() (min, max, and answer) should be initialized outside of onClick() or they will be reset to the default values with each click which I'm pretty sure you don't want (thanks to 323go for pointing that out).

How to wait till one of the buttons is clicked?

I am working on a project and have stuck at a point. I am working with Java Swing and this is the Problem:
When the user clicks on readMore button, I am creating an instance of class VerifyFF. Now, this class creates a frame which has an input field and two buttons namely cancel and continue. If the user presses cancel, then the frame disposes and nothing needs to be done. If he enters the correct password in the text field and then presses cont, I need to check whether the password is correct or not. For this I am using a boolean variable named as verified.
When the password entered is correct then the value of verified is set to true else nothing happens. The user gets and prompt of wrong password and again he can enter the correct password or can press cancel.
Now, in the class where I am creating the instance of VerifyFF class, I want to check whether the entered password was correct or not, hence I am checking for the value of variable boolean (which is also static). The trouble is, when the constructor of VerifyFF runs, there is nothing which stops the execution and waits for the user to enter something. Both the checking is done inside the function
JButton.addActionListener(new ActionListener()
{
};
The code in class instantiating the variable is:
VerifyFF vff = new VerifyFF();
if(vff.verified)
readMore();
Whenever I run this code, it doesn't waits to see whether any button is placed or not. I want to know how I can make it to wait till some button is pressed.
You don't have to wait until somebody pressed the button. Just move your
if(vvf.verified) readMode();
into your action listener for 'continue' button.
I am not sure of the problem. But maybe you should reconsider your implementation. In the constructor do just the first display then have a function that provides more whenever user clicks on more and password was correct.
You really do not need to stop constructor from being constructed, this sounds bad.
Good luck, Boro.
Your class should have a validatePassword method, which could be called on the click of the continue button.
class VerifyFF implements ActionListener {
private static final String ACTION_CONTINUE = "CONTINUE";
private JButton continueBtn = null;
private static boolean valid = false;
public VerifyFF() {
this.continueBtn = new JButton("Continue");
this.continueBtn.setActionCommand(VerifyFF.ACTION_CONTINUE);
this.continueBtn.addActionListener(this);
}
public static boolean validatePassword() {
//Validates the password field...
}
void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals(VerifyFF.ACTION_CONTINUE)) {
VerifyFF.valid = VerifyFF.validatePassword();
}
}
}
This way, the validate method is called on the press of the Continue button. and you can then do whatever you need according to the boolean 'valid'

Categories

Resources