开发者

Problem managing two activities in Android

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.

Class Loggs

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);
    }

}

Class Model

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 开发者_如何学PythonModel");       
        log.startGame();    
    }
}


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜