0

I am facing issue of NullPointerException. In my app I have two classes MainActivity and Test. I am creating object main of MainActivity inside Test class. When I call display method of MainActivity inside Test class main.display(); I get the NullPointerException. Please check my sample code below and recommend me changes where I am doing wrong.

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();
        }
2
  • 1
    you should not create an instance of main activity. activity is started by startActivity Commented Aug 26, 2013 at 9:44
  • where is the code & logcat ? Commented Aug 26, 2013 at 9:46

1 Answer 1

1

Do like this

do nor create instance of MainActivity class.

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

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.