Comparing variables - android

I'm writing a game and I am storing the players top score as a SharedPrefrence. I am using this method so that when the user exits the application, his top score stays. I have everything coded up until that point. I now want to implement a way to display the new top score when the player plays the game again. The logic behind this is that If the first top score is greater than zero, display the first top score. Then when the game is played again, if the second top score is greater than the first top score, display the second top score, else display the first top score. In my head, I would think a simple If/else statement would suffice, but my problem comes into play when declaring the first variables. I wrote the following code, but it doesn't seem to work. It just displays the new score--even if it is a lower value than the first score which is what I don't want. Any help would be much appreciated. Code:
TextView textSavedWeek2ms2_1 = (TextView)findViewById(R.id.ts02);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedWeek2ms2_1 = sharedPreferences.getString("top_score", "");
String topscore = strSavedWeek2ms2_1;
int topscore1 = Integer.valueOf( topscore);
if (topscore1 > 0 )
{
textSavedWeek2ms2_1.setText(topscore);
}
else
textSavedWeek2ms2_1.setText("0");
}

This is probably unintended:
if (topscore2 > topscore2){

I think you made a typo....
if (topscore2 > topscore2)
{
textSavedWeek2ms2_1.setText(topscore);
}
So it should be
if (topscore2 > topscore1)
{
textSavedWeek2ms2_1.setText(topscore);
}

Related

Setting Text Based on values held in ArrayList

This is driving me a little mad since I know this should be very simple but I am not getting the desired affect.
I have the following arraylist
private List<String> tagStringArray = new ArrayList<>();
Then later I have a method that creates dynamic buttons, based on ID values pulled across from my Retrofit instance.
In my method, I have a count to help me set the title of the button but I also add the values of count to an ArrayList for use in another method.
I have taken a snip of relevant information from the method mentioned.
count = 1;
if (!questionNumber.equals("") && !questionNumber.equals(null)) {
for (final Object value : list) {
try {
/*Dynamically create new Button which includes the question number
*/
final AppCompatButton btn_question = new AppCompatButton(getActivity());
/*LayoutParams (int width, int height,float weight)
As LayoutParams is defaulted in px, I have called a method called dpToPX to make sure
the dynamically added EditText is the same size on all devices.
*/
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(dpToPx(280), dpToPx(45), 1);
btn_question.setBackgroundColor(Color.parseColor("#3B5998"));
btn_question.setTextColor(Color.WHITE);
btn_question.setText("Question "+count);
//set the Tag based on its position in the XML
tagStringArray.add(String.valueOf((count)));
count++;
If a user clicks on say Question 1 Button, I want my fragment to say Question 1, so to try and achieve that, I have tried doing the following:
String tags = String.valueOf(tagStringArray);
tags = tags.substring(1, tags.length() -1);
String[] currentTag = tags.split(",");
if (currentTag[0].contains("1")) {
tv_setQuestions_edit.setText("Question 1");
}else if(currentTag[1].contains("2")) {
tv_setQuestions_edit.setText("Question 2");
}
But this will always set the title to Question 1 and I am not sure what is going wrong.......
If I use the following toast Toast.makeText(getActivity(), Arrays.toString(currentTag), Toast.LENGTH_LONG).show(); it shows [1,2] so I know they are being added ok.
I did look into using tags by doing:
public static int KEY_COUNT=0; public static int KEY_VALUE=1;
btn_question.setTag(KEY_VALUE,value);
btn_question.setTag(KEY_COUNT,count);
But for some reason, when I add more than one tag (as I need a minimum of 2), my dynamic button is missing from the layout. But for some reason when only 1 tag - like this btn_question.setTag(value); is used, it shows up fine (I have a feeling its some issue with my fragment). Therefore I am trying to think of a workaround in the meantime.
Any help or guidance would be really appreciated.
It's because
currentTag[0].contains("1")
is always true. The first item of currentTag always contains "1".
Instead of doing this, why don't you just do String titleForFragment = myButton.getText() in the onClick method for the button? That way, you can set the same onClickListener on all the buttons, and it will reduce the amount of code you need to write.

How to make a button give different results everytime when user tap it?

I have a button and I want it to change the text that I positioned above the button to something random everytime the user press it. How can I do it?
I want to look something like this:
"Hello"
**press**
"Why did you press?"
**press**
"Don't do that again, or..."
**press**
"You just did!"
Here is the code of the button and the text.
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
textChange.setText(string.textChange2);
}
}
);
There is no magical way to have it randomly change the text, you have to program it to do that. You are going to have to create an array of responses and then in the button's code, tell it to cycle through those responses. So for example:
private String[] responseArray = {"Hello", "Why did you press?", "Don't do that Again", "You Just did!" }
private int numTimesPressed = 0
dontPressButton.setOnClickListener(
//Sets the button to wait for the press
new Button.OnClickListener(){
public void onClick(View V) {
//Selects the text field to be changed
TextView textChange = (TextView) findViewById(R.id.textChange);
//Changes the text
//note this line will cause an error if there is not enough values in the array. You would have to write a catch for this
textChange.setText(responseArray[numTimesPressed++]);
//if you want random, you'll have to change the array index you are accessing to random value between the array's bounds
}
}
);
You'll definitely need an array of string responses. Afterwards, the first approach I would use is to use a random number generator, and then just link it back to your array. Unfortunately I'm not able to write the code, since I don't know the exact syntax, but in pseudocode:
string array[x]={"Hello","Why did you press?",...};//Number of string responses (in this case it's 4)
int random_number;
random_number=RandomNumberGenerator(1,x);//1 and x are the lower and upper bounds
switch (random_number)://If you don't know, switch is basically a simplified if-else system
case 1:print "Hello";
.........
There are many random number generators online that you can use, depending on the language. Hope this helped!
P.S: Maybe you'll want to fine-tune your responses to make them more natural. For example, you probably want to re-roll your response if you get two of the same one in a row.

Changing ListPreference entries by code working only the second time

I want to change dinamically the list entries and entryvalues of a listpreference. Well, finally it works, the list changes, but the problem is that I can see the new values only when I click the second time or more in the listpreference in the preference screen.
The first time, the list is always the original list, from 1 to 10.
numeroIntentosLP.setOnPreferenceClickListener(new OnPreferenceClickListener()
{
#Override
public boolean onPreferenceClick(Preference preference)
{
CharSequence[] NuevosValores = new String[10 - LineaActual];
int Indice = 0;
for(int i = LineaActual + 1; i <= 10; i++)
{
NuevosValores[Indice++] = String.valueOf(i);
}
numeroIntentosLP.setEntries(NuevosValores);
numeroIntentosLP.setEntryValues(NuevosValores);
return true;
}
});
I have tried with numeroIntentosLP.setOnPreferenceChangeListener, but the same result.
LineaActual is an integer value that I passed from MainActivity to PreferenceActivity. This is useful to me to know the new start value for the list.
So, everytime I open the preference screen and I click for the first time in the listpreference, I always get numbers 1 to 10, but when I click again, no matter how many times, I get what I want, I mean the list from LineaActual to 10.
Thanks in advance.
Ok, I found the solution. It was as easy as put the code directly in the onCreate, not in the listeners.
Thank you samgak, I saw your answer a little bit late and you're right, thank you anyway.

Change Text in a same Layout

I'm Making simple app for project
That App contains lot of text so i want,
"when a button is pressed, text should Change in same layout"
like PowerPoint slide.
I want change text only not scroll.
Now i made my app, have lots of Windows or Layouts.
It is not looking good, too much layout in simple app so please help me .
Thanks in advance
Doing this is very easy, I will quickly walk you through the Algorithm:
Set a class level variable called as FLAG initialize it to 1.
Let us assume that FLAG = 1 will represent the first slide. FLAG = 2 the second slide and so on.
Now in your button click you can use a switch case or an if else condition, based on the value of the flag display the relevant text in textview.
Once done, increment the flag, for the next set of sentence(s).
Class level:
int FLAG = 1;
onCreate:
Initialize your textView:
TextView mtv = (TextView)findViewById(R.id.yourid);
Set a button click listener:
private View.OnClickListener slides = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(FLAG ==1)
mtv.setText("First slide");
else if(FLAG ==2)
mtv.setText("Second Slide");
//and so on...
FLAG = FLAG+1;//increment flag
}
};

How to make textView that is set dynamically appear when Tab is run?

Let me try to explain my question in detail.
I have 5 tabs and my Tab class is run after the Splash screen of my application, and the first tab will be displayed.
In my first tab, I have a class that contains a TextView that will display certain text under some condition (related to profile keyed in by the user in another class).
TextView duration = (TextView)view.findViewById(R.id.duration);
duration.setText(durationNumber);
if(week <= 12)
{
durationNumber = "Less than 12 weeks";
}
else
{
durationNumber = "More than 12 weeks";
}
When I run my application, the text does not appear, unless i navigate to other tabs and return to the first tab. I googled around and couldn't find a solution. I've tried using SharedPreferences but it didn't work. Perhaps I did it wrongly.
Why is this happening and how can I fix this?
What is the initial value of durationNumber? Is it null before it is set in the if-else loop? If it is null then the TextView will not appear (as there is no value to display).
You will have to set the TextView text again after the if-else loop. Try this...
TextView duration = (TextView)view.findViewById(R.id.duration);
if(week <= 12) {
durationNumber = "Less than 12 weeks";
} else {
durationNumber = "More than 12 weeks";
}
duration.setText(durationNumber);

Categories

Resources