Question

I have a inner static class which extends thread inside my main Activity. In this Thread, I need to call a non-static method from my main Activity.

As I see, I have 2 options:

  • Make my non-static method static: This option would not be feasible cause inside this method I call startActivityForResult and I can't call this in a static way.
  • Create an object of my main Activity inside the inner static class, and call the method via this object.

     MainActivity mActivity = new MainActivity();   
     //...   
     mActivity.method();
    

The one I'm using now is the second, but I have a doubt about it. If I do this, I understand that I'm creating a new instance of MainActivity, and doing this, are all definitions in onCreate method called? Or I'm just calling the method and the variables I'm using inside will be null?

UPDATE --

This is the inner class where I need to call the method from main. I need this to be static because the base functionality of the app needs it to be this way. Now I'm introducing a new method in main activity that must be called when an action happens inside the thread:

private static final class DetectionThread extends Thread {
    //...

    public DetectionThread(byte[] data, int width, int height) {

    }

    @Override
        public void run() {

        //DO STUFF HERE

        //Action happens and calls the method from main activity:
        SpeechWhenMotion();
        //...
        }
    }
}

And this is the header of the method which is defined in the main activity. Inside of it I'm calling to another method which starts activity for result, so this is the reason why I cannot set this method as static:

public void SpeechWhenMotion() {
    //...
}
Était-ce utile?

La solution 2

Pass a MainActivity instance to your static method. Then call .method() from that instance.

static void doSomething(MainActivity ma) {
  ma.method();
}

This, or the 2nd option that you posted.

Autres conseils

Assuming MainActivity is the outer class, I guess what you are looking for is

MainActivity.this.startActivityForResult()

Creating another object isn't the right solution.

And BTW, it's equally bad to create a class extending Thread. I don't see a reason you need to do so. For all you need to do unless sophisticated threading, all you need to do is to implement Runnable(). Doing so properly segregate your threading concern from your business logic.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top