从另一个类调用方法导致应用崩溃 [英] Calling a method from another class is causing app to crash
问题描述
我决定尝试使我的代码更加面向对象,并避免在另一个类中重复代码.
I decided to try and make my code more object oriented and avoid repetitive code in another class.
活动的源代码:
public class EasyMode extends MainActivity {
GameActivityPVP game = new GameActivityPVP();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
game.initializeButtons();
}
}
public class GameActivityPVP extends MainActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
程序第二次到达我尝试使用 game.methodName();
调用方法的那一行,程序崩溃了.没有编译错误或其他任何东西.我一般对编程都不熟悉,所以请放轻松,我尝试尽可能简化我的代码.
The second the program gets to the line where I try to call a method using game.methodName();
the program crashes. No compiling errors or anything.
I am new to programming in general so please take it easy on me and I tried to simplify my code as much as possible.
Android Monitor/logcat:
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
和
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
推荐答案
您可以通过创建父类的对象来使用其他类的方法.
You can use another class's method by creating object of parent class.
请参见以下示例;
这里您要使用'GameActivityPVP'类中的方法.因此,您只需要在此类中创建一个对象.
Here you want to use method from 'GameActivityPVP' class. So you need to create one object in this class only.
public class GameActivityPVP extends MainActivity {
public static GameActivityPVP mGameActivity;
public GameActivityPVP getInstance(){
return mGameActivity; // assign value in onCreate() method.
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
mGameActivity = this; // Do not forget this, otherwise you'll get Exception here.
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
现在像这样在另一个类"EasyMode"中使用此对象;
Now use this Object in another class 'EasyMode' like this;
if(GameActivityPVP.getInstance()!=null){
GameActivityPVP.getInstance().initializeButtons();
}
这篇关于从另一个类调用方法导致应用崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!