I'm a little confused about when a variable or a method should be static. I've developed an app with several classes, variables and methods, and very rarely use the keyword static. Yet it works satisfactorily. Could you tell me if I make mistakes and why. Here is a sample of my code:
public class GameActivity extends AppCompatActivity {
public String[] mots = {"AFTERNOON", "AIRPORT","AVENUE","BETWEEN", "BUS", "CAB", "COAST","DAY",
"DIFFERENCE","DOLLARS","ENGLISH","FRENCH","GOOD","GOODBYE","HOUR","IMPROVE","LATER",
"LOCAL","MARGARET","NAME","NINE","NUMBER","ONLY","PHONE","PLANE","SAME","SHARE",
"SIDEWALK","STATES","SUNDAY","THERE","TIME","TWELVE","UNITED","UNIVERSITY","VERY",
"WEST","WHEN","WOMAN","YOUNG"};
public String[] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
public String mysteryWord = "vide";
//public int nombreDeLettres;
public int numeroImage = 1;
public boolean jeuFini = false;
public int lettresDevinees = 0;
public int wins = 0;
public int losses = 0;
public int numberOfMots;
int numeroAuHasard;
public Boolean maLettreAServi = false;
public ArrayList<CharSequence> lettresEssayees = new ArrayList<>();
public Button monBouton;
public TextView monTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder()
.addTestDevice("AC98C820A50B4AD8A2106EDE96FB87D4") // adds my test phone
.build();
mAdView.loadAd(request);
// une des solutions pour rendre la zone trado scrollable
TextView myXmlContent = (TextView)findViewById(R.id.zone_trado_scrollable);
myXmlContent.setMovementMethod(new ScrollingMovementMethod());
// écouteurs de tous les boutons actifs
ecouteursDeBoutons();
}
// joue une lettre
public void playLetter(final String letter) {
Resources res = getResources();
final int resId = res.getIdentifier(letter, "id", getPackageName());
monTextView = (TextView) this.findViewById(R.id.zone_trado_scrollable);
final TextView maLettre = (TextView) this.findViewById(resId);
maLettre.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!jeuFini) { // il faut mettre ce test _dans_ le onClick(View v)
if (!mysteryWord.equalsIgnoreCase("vide")) {
if (!lettresEssayees.contains(maLettre.getText())) {
// on teste que la lettre n'a pas déjà été essayée
maLettreAServi = false;
// boucle de test de lettre
for (int i = 0; i < mysteryWord.length(); i++) {
if (String.valueOf(mysteryWord.charAt(i)).equals(maLettre.getText())) {
int j = i + 1; // car dans le layout xml les id des positions commencent à 1
//monTextView.append("\nyou correctly found " + maLettre.getText() + " at position " + j);
final int resId = getResources().getIdentifier("position" + j, "id", getPackageName());
final TextView lettreADeviner = (TextView) GameActivity.this.findViewById(resId);
lettreADeviner.setText(maLettre.getText());
maLettreAServi = true;
lettresDevinees++;
}
}
maLettre.setText(""); // on efface de l'alphabet la lettre essayée
lettresEssayees.add(maLettre.getText());
// on la met dans l'arraylist lettresEssayees
// afin de ne pas la réessayer
// noter que java comprend qu'il s'agit d'un caractère et non d'une string
// test pour effacer de l'alphabet une lettre qui a servi
if (!maLettreAServi) {
// incrémenter le pendu
numeroImage++;
if (numeroImage < 10) {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu" + numeroImage, "drawable", getPackageName());
monImage.setImageResource(imageId);
} else {
ImageView monImage = (ImageView) findViewById(R.id.imagePendu);
final int imageId = getResources().getIdentifier("pendu10", "drawable", getPackageName());
monImage.setImageResource(imageId);
jeuFini = true;
monTextView.setText(Html.fromHtml("<font color=\"red\">you lost</font>"));
monTextView.append("\nthe word was "+mysteryWord);
losses++;
TextView nombrePertes = (TextView) findViewById(R.id.nr_losses);
nombrePertes.setText("" + losses); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
// test qu'on a trouvé le mot mystère
if (lettresDevinees == mysteryWord.length()) {
jeuFini = true;
// randomisation des félicitations
Random generator = new Random();
int randomIndex = generator.nextInt(3);
if(randomIndex == 0){
monTextView.setText(Html.fromHtml("<font color=\"blue\">bravo!</font>"));}
else if(randomIndex == 1){
monTextView.setText(Html.fromHtml("<font color=\"blue\">fantastic!</font>"));}
else if (randomIndex == 2) {
monTextView.setText(Html.fromHtml("<font color=\"blue\">you won</font>"));}
// rappel de ce qu'était le mot à deviner
monTextView.append("\nthe word was indeed " + mysteryWord);
String son = mysteryWord.toLowerCase()+"1";
final int resRaw = getResources().getIdentifier(son, "raw", getPackageName());
final MediaPlayer mp = MediaPlayer.create(GameActivity.this, resRaw);
mp.start();
wins++;
TextView nombreGains = (TextView) findViewById(R.id.nr_wins);
nombreGains.setText("" + wins); // pas réussi à utiliser toString(), alors j'utilise cette converstion
}
}
} else {
monTextView.setText("click on Select word first");
}
}
}
});
}
...
}
The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. if we talk about static variable then we difine it as The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
and if we talks about it uses: when you want to share your variable or methods only single copy through out the class without creating different copy, you should use static.
Advantages It makes your program memory efficient (i.e it saves memory).
A static variable can be accessed directly with its class name, and it will have a single instance.
YourActivity.staticVariableName=something;
It is helpful for accessing a variable from anywhere i the application. But beware it has a lifetime until your whole Application ends. So it consumes that memory for a whole application lifetime. So use it by keeping that in mind.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With