Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving logic from MainActivity to another class in Android

Tags:

java

android

I have a simple logic on my app that looks for a certain pitch.
The problem is that the logic is in the OnCreate method of the app (it has to detect the pitch the moment the application is running).
It is a little bit ugly as I plan to add some more logic as the application starts.
Does anyone have any advice of how to move that code to a different class so that it could be invoked from there?
The class still has to access views in the main activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
    dispatcher.addAudioProcessor(new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, new PitchDetectionHandler() {

        @Override
        public void handlePitch(PitchDetectionResult pitchDetectionResult,
                                AudioEvent audioEvent) {

            final float pitchInHz = pitchDetectionResult.getPitch();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Float value = pitchInHz;
                    Toast.makeText(getApplicationContext(),value.tostring(), Toast.LENGTH_SHORT).show();
                }
            });

        }
    }));
    foo = new Thread(dispatcher,"Audio Dispatcher");
    foo.start();
}
like image 427
toothpick Avatar asked Dec 18 '25 09:12

toothpick


1 Answers

Basically, you have two options to make your code cleaner.

  1. Move all the code in onCreate() (except first two lines) into another method, let's say lookForPitch(). Then you can call it right in onCreate().
  2. If you plan to create more methods that focus on audio processing, you can create separate class, for example AudioUtils.java. This util class should contain public static methods, that you can invoke from any place in your code. In case of onCreate() you may call it like this: AudioUtils.lookForPitch(). Also if you want to handle Views, that are accessible only in your Activity, you can pass them as argument. So your method in AudioUtils can look like this:

    public static void lookForPitch(TextView myTextView) {
        // your code goes here
    }
    
like image 196
Jerry Avatar answered Dec 19 '25 23:12

Jerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!