1. Download our Official Android App: Forums for Android!

Apps mageButton as global variable not working... why??

Discussion in 'Android Development' started by jesb, Jun 1, 2011.

  1. jesb

    jesb Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    5
    Joined:
    Jun 1, 2011

    Jun 1, 2011
    5
    0
    5
    i'm very new to android, and basically modifying an app i find on
    textbook. This app contain a single ImageButton on the center of the
    screen. it will detect the ringer mode of the phone, and when clicked,
    it will change the ringer mode from silent to normal or normal to
    silent.

    i declare ImageButton twice. Once in each procedure. If i declare
    ImageButton as global variable just like the variable silent and
    ringer, the app will fail. can somebody tell me why this is?

    private AudioManager ringer;
    private boolean silent;
    ImageButton imgBtn=(ImageButton) findViewById(R.id.imgBtn);

    this is the working version of the app.

    public class MainActivity extends Activity {

    private AudioManager ringer;
    private boolean silent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ringer=(AudioManager) getSystemService(AUDIO_SERVICE);
    checkPhoneStatus();
    setButtonListener();
    }

    private void checkPhoneStatus(){
    int ringing=ringer.getRingerMode();
    if(ringing==AudioManager.RINGER_MODE_NORMAL)
    silent = false;
    else
    silent=true;
    }
    private void setButtonListener(){
    ImageButton imgBtn=(ImageButton) findViewById(R.id.imgBtn);
    imgBtn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {
    // TODO Auto-generated method stub
    if(silent){
    ringer.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
    silent=false;
    }else{
    ringer.setRingerMode(AudioManager.RINGER_MODE_SILENT);
    silent=true;
    }
    changeButton();
    }
    });
    }
    private void changeButton(){
    ImageButton imgBtn=(ImageButton) findViewById(R.id.imgBtn);
    if(silent)

    imgBtn.setImageDrawable(getResources().getDrawable(R.drawable.phone_silent));
    else

    imgBtn.setImageDrawable(getResources().getDrawable(R.drawable.phone_on));

    }
    @Override
    protected void onResume(){
    super.onResume();
    checkPhoneStatus();
    changeButton();
    }
    }
     

    Advertisement

  2. tonylukasavage

    Rank:
    None
    Points:
    5
    Posts:
    2
    Joined:
    Jun 3, 2011

    findViewById() will fail if you have not set the content of the Activity yet. That call needs to come after the setContentView() call in the onCreate() method.
     

Share This Page

Loading...