MohammadLord MohammadLord - 4 months ago 18
Android Question

button OnClickListener works only one time android

i have activity below. when i run the app it only works one time and when i press

storeBTN
or
retrieveBTN
after first time i see no changes in
Textview
and no log about running
store()
and
retrieve()
functions.

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button storeBTN = (Button) findViewById(R.id.button);
storeBTN.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
EditText et = (EditText) findViewById(R.id.editText);
int i = Integer.parseInt(et.getText().toString());
store(i);
}
});
Button retrieveBTN = (Button) findViewById(R.id.button2);
retrieveBTN.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View v) {
retrieve();
}
});

}
public void store(int newHighScore){
Log.d("Meeeeee", "store: "+newHighScore);
setContentView(R.layout.activity_main);
SharedPreferences sharedPref = this.getPreferences(this.MODE_APPEND);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
boolean b = editor.commit();
Log.d("Meeee", "store: commited? "+b);
retrieve();
return;
}
public void retrieve(){
SharedPreferences sharedPref = this.getPreferences(this.MODE_APPEND);
int defaultValue = getResources().getInteger(R.integer.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
Log.d("meeee", "retrieve: "+highScore+" in mode: "+this.MODE_APPEND);
TextView scoreTV = (TextView) findViewById(R.id.textView);
scoreTV.setText(highScore+"");
return;
}

}

Answer

Remove

setContentView(R.layout.activity_main);

from store() method