When I try to use the onClickListener method for a button, variable outside of any onCreate or onPause or onAnything method, it does not work. I also cannot even set the value of a button variable outside of an “onAnything” method. Help would be great.
Thanks!
public class StartingPoint extends Activity {
/** Called when the activity is first created. */
int counter;
Button add= (Button) findViewById(R.id.bAdd);
Button sub= (Button) findViewById(R.id.bSub);
TextView display= (TextView) findViewById(R.id.tvDisplay);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("phase", "on create");
counter=0;
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText(""+counter);
display.setTextSize(counter);
Log.i("phase", "add");
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText(""+counter);
display.setTextSize(counter);
display.setTextColor(Color.GREEN);
Log.i("phase", "sub");
}
});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i("phase", "on start");
SharedPreferences prefs = getPreferences(0);
int getfromfile = prefs.getInt("counter_store", 1);
counter=getfromfile;
display.setText(""+getfromfile);
display.setTextSize(getfromfile);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.i("phase", "on stop");
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("counter_store", counter);
editor.commit();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
counter=0;
Log.i("phase", "on destroy");
}
}
One thing I notice about your code is that you are initializing your views when you declare them, which is before you set the content view. Find view by id will not work until after you do so. Change it so you declare them like
Also, the error message you are seeing is because you cannot execute that statement outside of a method. You should be doing it inside
onCreateanyway.