Reputation: 176
I have my main class setup and a worker thread, one of my early requests that I make in run()
is to call my second class called login. I do this like so:
login cLogin = new login();
cLogin.myLogin();
class login looks like this:
package timer.test;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
public class login extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
}
public void myLogin() {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// set the message to display
alertbox.setMessage(this.getString(R.string.intro));
// add a neutral button to the alert box and assign a click listener
alertbox.setNeutralButton("Register New Account",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
}
});
// add a neutral button to the alert box and assign a click listener
alertbox.setNegativeButton("Login",
new DialogInterface.OnClickListener() {
// click listener on the alert box
public void onClick(DialogInterface arg0, int arg1) {
// the button was clicked
}
});
// show it
alertbox.show();
}
10-01 14:33:33.028: ERROR/AndroidRuntime(440):
java.lang.RuntimeException: Unable to start activity ComponentInfo{timer.test/timer.test.menu}:
java.lang.IllegalStateException:
System services not available to Activities before onCreate()
I put onCreate
in but still having the same problem. How can I fix this?
Upvotes: 1
Views: 272
Reputation: 11844
You cannot do it this way simply because you are using the context
AlertDialog.Builder alertbox = new AlertDialog.Builder(this); //this is the activity context passed in..
The context is not available until Activity onCreate is called via startActivity. and not by constructing an new instance of the login object, you can try passing in an context from the activity calling this method
public void myLogin(Context context) {
// prepare the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(context);
//blah blah blah...
}
yes and never construct an activity instance via the constructor.. -.-
Upvotes: 1
Reputation: 1490
You have a couple of options:
1) Move your public void myLogin() {..} to your main activity. I recommend this solution since you don't need another activity for your purposes.
2) Call startActivity on your login class before calling the myLogin(). Since you inherite from Activity onCreate needs to be called before you call anything else. That's why you get the exception. startActivity is called like this:
Intent i = new Intent(this, login.class);
startActivity(i);
Upvotes: 1