I am developing an android application for a friend of mine that is a football trainer.
He asked me to create an application that is more of a table to count the stats of the players. The image below should clear things up:
Table of the application
As you can see, every time I press the upper left button I want to add a new player two a new row with a decrement button a counter and an increment button below each stat column.
I can currently do that but each player has 10 different column counters. So considering that I want to add 25 players for the maximum I should copy my code (250 times) with an incremented value in order to gain the same functionality for each player.
I've thought about using an array or a hashmap I'm just not sure what's the best practise to do it. Any suggestions are more than welcome.
Pre-declared variables for one player:
private int counter1 = 0;
private int counter2 = 0;
private int counter3 = 0;
private int counter4 = 0;
private int counter5 = 0;
private int counter6 = 0;
private int counter7 = 0;
private int counter8 = 0;
private int counter9 = 0;
private int counter10 = 0;
private TextView textCounter1;
private TextView textCounter2;
private TextView textCounter3;
private TextView textCounter4;
private TextView textCounter5;
private TextView textCounter6;
private TextView textCounter7;
private TextView textCounter8;
private TextView textCounter9;
private TextView textCounter10;
Routine that needs to be copied 250 times:
if (playersAdded == 1) {
//Set 1
ImageButton decrementButton1 = new ImageButton(getApplicationContext());
decrementButton1.setImageDrawable(decrementDrawableScaled);
decrementButton1.setLayoutParams(layoutParams);
textCounter1 = new TextView(getApplicationContext());
textCounter1.setText(String.valueOf(counter1));
textCounter1.setLayoutParams(layoutParams);
ImageButton incrementButton1 = new ImageButton(getApplicationContext());
incrementButton1.setImageDrawable(incrementDrawableScaled);
incrementButton1.setLayoutParams(layoutParams);
decrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (counter1 > 0) {
counter1 -= 1;
textCounter1.setText(String.valueOf(counter1));
}
}
});
incrementButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter1 += 1;
textCounter1.setText(String.valueOf(counter1));
}
);
//End of Set 1
}
Make class Player. (Learn Object-oriented programming)
Make row for one player. (Learn how to create listView, this tutorial should help you, or just google android listView)
Make listView with players row.
Related
In my quiz app I get points for my buttons and checkboxes, but the edittext questions aren't being counted when they are correct. Here's my java code for one edittext field:
EditText question2_answer = findViewById(R.id.question2_answer);
if (question2_answer.equals("Surrounding membrane, Cytoplasm and Nucleus")) {
question2_score = 1;
} else {
question2_score = 0;
}
you should use getText().toString() so you can get entered text in the EditText
EditText question2_answer = findViewById(R.id.question2_answer);
if (question2_answer.getText().toString().equals("Surrounding membrane, Cytoplasm and Nucleus")) {
question2_score = 1;
} else {
question2_score = 0;
}
I have a for loop within my main activity that is used to randomly shuffle/reassign the values within an array at the beginning of every time the application is opened.
I was told that for loops in Android Studio could only exist within a method (after getting errors when it was placed without one), but by doing so the random shuffling of the array is not carried over to the rest of the click events that are outside of the method and it just continues to output the same originally assigned values of in the array.
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
The click events that are using the values from this array are like this one:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View b) {
one.setVisibility(View.INVISIBLE);
counter++;
money[0] = 0;
Context one = getApplicationContext();
CharSequence message1 = "$1";
int duration = Toast.LENGTH_LONG; //this could also be a number
final Toast one1 = Toast.makeText(one, message1, duration);
one1.show();
for (int x = 0; x < 16; x++) {
sum += money[x];
}
banker = sum / 16;
Context oney = getApplicationContext();
CharSequence message1y = "The Banker offers you $" + banker + " for your case.";
int durationy = Toast.LENGTH_LONG; //this could also be a number
final Toast one1y = Toast.makeText(oney, message1y, durationy);
one1y.show();
}
});
The aim was that if I were to click this button this time the money output was something like $500, and the next time I opened the application it would randomly shuffle and I might get a new value like $1.
You might want to check out Collections.shuffle() instead of implementing it (don't reinvent the wheel etc).
Sounds like what you want to do is call the shuffle method from inside onCreate() and onResume()
You should do the shuffle inside of the "onCreate" method.
public void onCreate(Bundle savedInstanceState){
...
int[] money = {1,10,5,2,20,500,50,100,1000000,5000,1000,50000,100000,500000,250000,10000};
int swap1;
int swap2;
int temp;
Random random = new Random();
void what(){
for (int j=0;j<16;j+=1)
{
swap1 = random.nextInt(16);
swap2 = random.nextInt(16);
temp = money[swap1];
money[swap1] = money[swap2];
money[swap2] = temp;
}
}
}
Thanks for all suggestion and thoughts i finally achieved it by yours suggestions and it was a simple logic work to solve the problem. I want to share it if any one want to create custom Health Bar , but it is not suitable for 100 HP because then you have to write 100 IF statements,
Idea was to create simple custom Healthbar and decrease it by pressing button clicks.
This link also help me a lot.
HealthBar
Code
private TextView Message,result;
private Button play;
private float maxHP = 10;
private float currentHP = maxHP;
//private float percentHP = (float) (currentHP/maxHP);
private int user_shield;
private float healthBar;
private ImageView shieldusb1,shieldusb2,shieldusb3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_one);
Initialize();
}
private void Initialize(){
user_shield = R.raw.shield_blue;
shieldusb2 = (ImageView) findViewById(R.id.shield_b2);
shieldusb1 = (ImageView) findViewById(R.id.shield_b1);
shieldusb3 = (ImageView) findViewById(R.id.shield_b3);
result = (TextView) findViewById(R.id.result);
play = (Button) findViewById(R.id.playButton);
play.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
play();
}
});
}
public void play(){
{
healthBar=0;
currentHP = (float) (currentHP - 0.5);
//currentHP -= 1;
if(currentHP <= 0) //if the player died
{
currentHP = 0; //set his HP to zero, (just in case)
Message.setText("You died! :P"); //add any extra death-code here
//update the healthBar
result.setText ("WIN POINTS");
}
updateHealthBar();
}
}
private void updateHealthBar() {
// percentHP = currentHP / maxHP;
healthBar = currentHP;
if(healthBar<9.6){
shieldusb1.setVisibility(View.GONE);
}
{
if (healthBar<=9){
shieldusb2.setVisibility(View.GONE);
}
if (healthBar<=8.6){
shieldusb3.setVisibility(View.GONE);
}
}
}
My guess, is you need to remove the else if and make it just if because if you execute first statement where <= 1, else if will never get executed.
private void updateHealthBar() {
percentHP = currentHP / maxHP; / calculating points
healthBar = percentHP;
if(healthBar<=1){ // Hiding first Image View
shieldusb1.setVisibility(View.GONE);
}
if (healthBar<=0.9){
shieldusb2.setVisibility(View.GONE); // How to Hide this Image View after button click
}
}
Your healthBar is of int type, so checking against 0.9 is the same as checking against 1.
Also, in your conditions, you're first checking:
if (healthBar <= 1)
If this condition is true, you're hiding shieldusb1, and you will never reach second condition because you have used else. What you can do is to remove else in front of second condition, but as said above, your healthBar is int, so the second condition is basically the same as the first. Change healthBar to double.
You need to adjust these conditions
if(healthBar<=1)
...
else if (healthBar<=0.9)
Even if healthBar<= 0.9 evaluates true, healthBar<=1 is also true so it will always enter the first if
You check if healthBar is <= 1, and after if is <= 0.9... But this case never verify, cause 0.9 is < 1, so it always choose the first option!
Change your first if for check values between 1 and 0.9, and it will work!
It's only logical problem. Change if/else if block for if/if.
if(healthBar<=1)
shieldusb1.setVisibility(View.GONE);
if (healthBar<=0.9)
shieldusb2.setVisibility(View.GONE);
I inflate an EditText and I setId(i++) | static int i = 0;
and this is the code :
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addOne = layoutInflater.inflate(R.layout.row, null);
final EditText textOut = (EditText)addOne.findViewById(R.id.textout);
Button buttonRemove = (Button)addOne.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((LinearLayout) addOne.getParent()).removeView(addOne);
}
});
container.addView(addOne);
textOut.setId(i++); }});
so, if I add an EditText, the Id will be 0 and if I add another EditText, the Id will be 1 .. etc
so, the user can select how many EditText he want, right ?
if the user add 3 EditText for example
How can my code knows ?
for example, if I want sum all the values of EditText, and the user add 3 EditTixt
I will do this
( EditText one = (EditText)findViewById(0) ) + ( EditText dodo = (EditText)findViewById(1) ) + ( EditText dodo = (EditText)findViewById(2) )
But, if I don't know how many EditTixt the user will add !
what can I do ?
thank you.
int count = 0;
int childcount = container.getChildCount();
for (int i=0; i < childcount; i++){
View v = container.getChildAt(i);
if(view.getTag.equals("edittext"){
count ++;
}
}
and change this line in your code
final View addOne = layoutInflater.inflate(R.layout.row, null);
addOne.setTag("edittext");
count return you total edittext added by user
take look on this code it will count edit text for you in your layout container
first you need to making changed in your code like this and it worked with me fine :
final ViewGroup addOne = (ViewGroup) layoutInflater.inflate(R.layout.test, null);
int count = 0 ;
for (int i = 0; i < addOne .getChildCount(); i++) {
if(addOne .getChildAt(i).getClass().getSimpleName().equals("EditText"))
count ++ ;
}
Okay so put simply i am trying to save and then load data to and from a NumberPicker. The NumberPicker values are set initially with a string array as specific values are required to be chosen from in the NumberPicker setDisplayedValues() method is used.
I dont have any trouble saving its just when it comes to loading. because im guessing i need to give the index of the position in which that value is found in the array. This is what i have been trying but to no avail
minSpinNP.setValue(Integer.parseInt(spinValues[minSpinPos]));
maxSpinNP.setValue(Integer.parseInt(spinValues[maxSpinPos]));
Ibelieve numberPicker must take an int or an array of strings.
I am also getting this error when loading the prefs()
12-12 19:57:34.724: E/AndroidRuntime(7612): Caused by: java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
12-12 19:57:34.724: E/AndroidRuntime(7612):
at android.app.SharedPreferencesImpl.getInt(SharedPreferencesImpl.java:240)
12-12 19:57:34.724: E/AndroidRuntime(7612):
at sweetbix.android.shredbox.JumpSettings.loadPrefs(JumpSettings.java:228)
any help would be appreciated :)
global variables
SeekBar switchSlider;
RadioGroup directionRadioGroup;
RadioButton fsRadioBtn;
RadioButton bsRadioBtn;
RadioButton fsBsRadioBtn;
RadioButton dirOffRadioBtn;
SeekBar corkSlider;
SeekBar spinSlider;
SeekBar grabSlider;
NumberPicker minSpinNP;
NumberPicker maxSpinNP;
Button saveBtn;
boolean safe;
int maxSpinPos;
int minSpinPos;
private int switchProbability;
private int corkProbability;
private int spinProbability;
private int grabProbability;
private int spin = 0;
private int minSpin;
private int maxSpin;
private String[] spinValues = new String[8];
strings added to spinValues
for (int i = 0; i < spinValues.length; i++) {
String rotation = Integer.toString(spin += 180);
spinValues[i] = rotation;
}
the save method used,
private void savePrefs(String key, int value){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor editor = prefs.edit();
editor.putInt(key, value);
editor.commit();
}
onchangelistener for the numberpicker, somecode commented but shows what i have tried.
maxSpinNP.setOnValueChangedListener(new OnValueChangeListener(){
#Override
public void onValueChange(NumberPicker picker, int oldVal,
int newVal) {
// TODO Auto-generated method stub
//maxSpin = Integer.parseInt(spinValues[maxSpinNP.getValue()]);
//maxSpin = spinValues[maxSpinNP.getValue()];
maxSpinPos = Arrays.asList(spinValues).indexOf(maxSpin);
Toast.makeText(JumpSettings.this,"maxspinpos:"+ maxSpinPos,
Toast.LENGTH_SHORT).show();
}
});
calling the save method
savePrefs("MIN_SPIN_JUMPS", minSpinPos);
savePrefs("MAX_SPIN_JUMPS", maxSpinPos);
finally calling the loadprefs method, more code commented
private void loadPrefs(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
switchProbability = prefs.getInt("SWITCH_JUMPS", 35);
switchSlider.setProgress(switchProbability);
corkProbability = prefs.getInt("CORK_JUMPS", 20);
corkSlider.setProgress(corkProbability);
spinProbability = prefs.getInt("SPIN_JUMPS", 80);
spinSlider.setProgress(spinProbability);
grabProbability = prefs.getInt("GRAB_JUMPS", 80);
grabSlider.setProgress(grabProbability);
minSpinPos = prefs.getInt("MIN_SPIN_JUMPS", 0);
maxSpinPos = prefs.getInt("MAX_SPIN_JUMPS", 7);
//minSpin = prefs.getString("MIN_SPIN_JUMPS", "180");
//minSpinNP.setValue(Integer.parseInt(spinValues[minSpinPos]));
//maxSpin = prefs.getString("MAX_SPIN_JUMPS", 1080);
//maxSpinNP.setValue(Integer.parseInt(spinValues[maxSpinPos]));
Log.e("min", "" + minSpinPos);
Log.e("max", "" + maxSpinPos);
//Log.e("prob", switchProbability + "");
}
this is line 228
minSpinPos = prefs.getInt("MIN_SPIN_JUMPS", 0);
solved it. i used this in the load preferences method
for( int i=0; i<spinValues.length ; i++ )
if( spinValues[i].equals(maxSpinPos) )
maxSpinNP.setValue(i);
numberpicker takes an int value and i thought i was getting an int value when i was trying to get the array index but i was actually getting the index and setting the variable to the value of that index
yay :)