0

我面临的问题NullPointerException。在我的应用程序中,我有两个类MainActivityTest. 我正在创建MainActivity内部Test类的主要对象。当我调用MainActivity内部Test类的显示方法时,main.display();我得到NullPointerException. 请检查下面的示例代码,并建议我更改我做错的地方。

public class MainActivity extends Activity {


    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // Fixed
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // orientation

        setContentView(R.layout.training_ten_position);

        Test test = new Test(10);

    }


    public  MainActivity()  {
        super();
    }
    public void display() {

    }


    }



public class Test {
        .
        .
        .
        MainActivity main;

        public Test(int duration) {
            // Initializing data member
            main = new MainActivity();
        }

        public void delay() {
            .
            .
            .
            main.display();
        }
4

1 回答 1

1

这样做

不要创建MainActivity类的实例。

public class MainActivity extends Activity{

 //Make Your Function static 

  public static void display(){
    //Do your code 
    // whatever variables or views you want to use in this method make them static
  }

}

public class Test extend Activity{
   //how call display function
   MainActivity.display();

}
于 2013-08-26T09:49:46.297 回答