开发者

Using Child Class In Android

Sorry, I'm a newbie to Java and Android...

I've made an app that has a big main activity, I'm wanting to split it up into some child classes to make things easier to read, edit etc.

From my main class I (think) I am instantiating, and calling the child class, from within OnResume :

  SetupButtons SetupButtonsObject = new SetupButtons ();
          SetupButtonsObject.buildthem();
开发者_Go百科

And in the child class I do:

        class SetupButtons extends main {

     void buildthem(){
//a load of things to setup buttons
}

}

The code I am using in buildthem() works fine when used in the main class, but is giving a nullpointer exception when used in the child class.

do I need to pass the main context to the child or something?

Many Thanks Tom


Anything you use in the childclass that is not set there, but set in the main class, you must in some way get from the main class. So yeah, you need some context.

But before you do that: you might want to divide your app in classes that are logical parts of your sollution, as you can read in any OOP description. So not just chop it up in parts because it makes it smaller, chop it up in logical units that are actual good objects.

A quick type, hope I did not make any mistakes here, but see comments in child class.

class Parent{
   public static int foo = 1;
   public static int bar = 0;

   public function somefunction(){
      bar = 1;
      myChild = new Child();
   }

}

class Child extends Parent{
   //you can find foo = 1
   //but not bar = 0;
}


The Activity class isn't supposed to be instantiated by developer directly, leave this work to the android. If you wish to split it up why do you extend your main activity? You rather need to divide your app in logical parts as Nanne said.


In same class you can call that method directly. Like buildthem();

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜