I’m very new to both android and java development. I am attempting to build an easy app. It is currently very easy but I cannot seem to get the code to run. As soon as I run the app in the emulator it spits out an alert saying my app has stopped.
Here is my code:
package com.example.ultimatescoreclock;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.os.CountDownTimer;
public class MainActivity extends Activity {
// variables for the clock
byte minRemaining = 0;
byte secRemaining = 0;
long msRemaining = 360000; // six minutes
TextView mainClock = (TextView) findViewById(R.id.clockMain);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public byte getMinutes(long millisUntilFinished) {
return (byte) (millisUntilFinished / 60000);
}
public void onMainClockClick() {
StringBuilder str = new StringBuilder("");
str.append(minRemaining + ":" + secRemaining);
mainClock.setText(str);
}
}
Could someone please let me know what silly mistake I have made here? FYI – My XML document has the onClick property set for the R.id.mainClock TextView.
has to be placed after
setContentView();This is because you first have to set the layout that your
Activityuses and only then can you work with it. What is happening is your Object is being created, and your global variable (mainClock) is accessing something that does not exist yet becauseonCreate()has not gotten called yet.So change
TextView mainClock = (TextView) findViewById(R.id.clockMain);toand onCreate() should look like.