Search code examples
androidmultithreadingandroid-activityfragmentthis

MainActivity.this call, in Fragment


I'm new in android. I have a code which is consisted ViewPager and TabLayout. And it has 4 Fragments. On my Fragment4 code, I want to use CircleProgressView which I got in GitHub. To use that code, I should use AsyncTask. And it has "MainActivity.this.runOnUiThread(new Runnable){}". But this code occurred error. The message is "MainActivity is not an enclosing class." I think it means MainActivity class could not be referred. How can I call "MainActivity.this.runOnUiThread()"? Please tell me how to fix code.

Here is a part of my code.

public class Fragment4 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment4, container, false);

    ...

    return rootView;

    }

    @Override
    public void onStart() {
        super.onStart();
    }

    private class LongOperation extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... params) {

            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mCircleView.setValue(0);
                    mCircleView.spin();
                }
            });

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            mCircleView.setValueAnimated(42);
        }
    }
}

Solution

  • MainActivity.this is just a way to get the Activity context, however there are multiple other ways to obtain this context.

    1. Use getActivity() to get the context from the current Activity
    2. Use getApplicationContext(), which is a different context which is the same for all activities but should work here too.
    3. If you use API 23 or above you can use getContext() from within a Fragment to get the current context.