Reputation: 2501
What I am trying to do is very simple. I created two classes A and B. I created a click handler in A which calls a function in B which in turn calls a function in A. In the called function in A I am create a button. My programs is being forced close when I try to push the button.
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class Loggs extends Activity {
Model model;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void clickHandler(View v)
{
model = new Model();
model.startGame();
//click();
}
public void startGame()
{
Log.d("Log","Reached start game");
click();
}
public void click()
{
Log.d("Log","Reached click");
Button btn =(Button)findViewById(R.id.startButton);
btn.setEnabled(false);
}
}
import android.app.Activity; import android.os.Bundle; import android.util.Log;
public class Model extends Activity{
Loggs log;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startGame() {
log= new Loggs();
Log.d("Logg","Reached start game Model");
log.startGame();
}
}
Upvotes: 0
Views: 131
Reputation: 20319
Its not really clear what you are trying to do here? Activities don't communicate with each other in this way. If you want one activity to start another you need to do so using Intents:
For example if you want to the Model activity from Loggs you would issue the following commands:
Intent i = new Intent(this, Model.class);
this.startActivity(i);
Although I'm not sure if this is what you are trying to do. As has been already said you should avoid circular dependencies.
Upvotes: 0
Reputation: 660
Look at the code. Doing "log = new Loggs();" does not call the "onCreate" method on Loggs. Which means that "setContentView" is never called.
At the Loggs#click method, the button that you get via "findViewById" will be null. As a result btn.setEnabled would cause a NullPointerException causing the program to crash.
WarrenFaith and blackbelt gives good advice. Read up on activities, when, how and why they should be used.
Upvotes: 0
Reputation: 157487
is R.id.startButton in R.layout.main? Than.. you cannot instantiate an activity with new, imo, because the default constructor for activity are private (i think). Take a look at intent
Upvotes: 1