1

I want to change the orientation of the screen by code with an AsynTask, but I noted that my app crashes if I put

getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

in public String doInBackground(String... params) or in public void onPostExecute(String s)

Instead this method works, for example, in a TabbedActivity class or in a Fragment class. Why doesn't this method work in AsynTask? I really need to use it!

This is the logcat

01-01 18:03:40.953 3646-3783/com.example.utente.progettigscorsipa E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                                Process: com.example.utente.progettigscorsipa, PID: 3646
                                                                                java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                                    at android.os.AsyncTask$3.done(AsyncTask.java:318)
                                                                                    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                                    at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
                                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                    at java.lang.Thread.run(Thread.java:761)
                                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setRequestedOrientation(int)' on a null object reference
                                                                                    at com.example.utente.progettigscorsipa.FotoCuboActivity$PlaceholderFragment$MultiplyTask.doInBackground(FotoCuboActivity.java:165)
                                                                                    at com.example.utente.progettigscorsipa.FotoCuboActivity$PlaceholderFragment$MultiplyTask.doInBackground(FotoCuboActivity.java:142)
                                                                                    at android.os.AsyncTask$2.call(AsyncTask.java:304)
                                                                                    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                                    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
                                                                                    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
                                                                                    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
                                                                                    at java.lang.Thread.run(Thread.java:761) 

01-01 18:03:41.340 3646-3682/com.example.utente.progettigscorsipa E/EGL_emulation: tid 3682: eglSurfaceAttrib(1146): error 0x3009 (EGL_BAD_MATCH) 01-01 18:03:41.340 3646-3682/com.example.utente.progettigscorsipa W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9637ab60, error=EGL_BAD_MATCH

public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    private boolean ciclo=true;
    private Activity activity;

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        switch (getArguments().getInt(ARG_SECTION_NUMBER))
        {
            case 1:
                SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("i",0);
                editor.commit();
                new MultiplyTask().execute();
                View rootView = inflater.inflate(R.layout.fragment_foto_cubo, container, false);
                return rootView;

            case 2:
                View rootView2 = inflater.inflate(R.layout.fragment_foto_cubo4, container, false);
                return rootView2;

            case 3:
                View rootView3 = inflater.inflate(R.layout.fragment_foto_cubo5, container, false);
                return rootView3;

            case 4:
                View rootView4 = inflater.inflate(R.layout.fragment_foto_cubo6, container, false);
                return rootView4;

            case 5:
                View rootView5 = inflater.inflate(R.layout.fragment_foto_cubo7, container, false);
                return rootView5;

            case 6:
                View rootView6 = inflater.inflate(R.layout.fragment_foto_cubo8, container, false);
                return rootView6;

            case 7:
                View rootView7 = inflater.inflate(R.layout.fragment_foto_cubo2, container, false);
                return rootView7;

            case 8:
                prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
                editor = prefs.edit();
                editor.putInt("i",7);
                editor.commit();
                new MultiplyTask().execute();
                View rootView8 = inflater.inflate(R.layout.fragment_foto_cubo3, container, false);
                return rootView8;

            default:
                View rootView0 = inflater.inflate(R.layout.fragment_foto_cubo, container, false);
                return rootView0;
        }
    }

    @Override
    public void onAttach(Activity activity1)
    {
        super.onAttach(activity1);
        activity = activity1;

    }

    public class MultiplyTask extends AsyncTask<String,String,String>
    {
        @Override
        public void onPreExecute()
        {
            super.onPreExecute();
            Toast.makeText(getActivity(),"Sto eseguendo",Toast.LENGTH_LONG).show();
        }

        @Override
        public void onPostExecute(String s)
        {
            super.onPostExecute(s);
        }

        @Override
        public String doInBackground(String... params)
        {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
            while(ciclo)
            {
                if(prefs.getInt("i",0)==7)
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                else
                    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            return null;
        }


    }
}
Curio
  • 1,331
  • 2
  • 14
  • 34
  • Put details of the crash for onPostExecute – weston Jan 01 '17 at 17:42
  • @weston now it works, but I didn't change nothing...before my app crashes both on the emulator and on my mobile – Curio Jan 01 '17 at 17:49
  • @weston But, can I put `getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);` in doInBackGround? – Curio Jan 01 '17 at 17:53
  • You said you did it. And there was a problem, so something's not right yes?, but I don't know everything, I rely on the details of the exception thrown to determine the problem. Also more code would be good. – weston Jan 01 '17 at 17:56
  • @weston I posted the logcat when my app crashes when I put setRequestedOrientation in doInBackground – Curio Jan 01 '17 at 18:05
  • `getActivity()` is returning `null` then, because `java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.setRequestedOrientation(int)' on a null object reference` – weston Jan 01 '17 at 18:06
  • @weston How can I resolve this problem? – Curio Jan 01 '17 at 18:08
  • [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – weston Jan 01 '17 at 18:08
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – weston Jan 01 '17 at 18:09
  • @weston I'll take note. Anyway, I solved the problem with `onAttach(Activity activity)`. I save the activity in a class variable and then I do `activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);` in doInBackground – Curio Jan 01 '17 at 18:18
  • Well, the class variable sounds like a very bad idea. If you want more help, post some actual code. – weston Jan 01 '17 at 18:21
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/132028/discussion-between-curio-and-weston). – Curio Jan 01 '17 at 20:15
  • [Asynctask on rotation](http://stackoverflow.com/questions/7128670/best-practice-asynctask-during-orientation-change) see this – skydroid Jan 02 '17 at 06:20

1 Answers1

0

I've had more success locking the screen in it's current orientation than to force an orientation (like you did with landscape) when using AsyncTask.

//lock screen orientation
private void lockScreenOrientation() {
    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    else setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
seekingStillness
  • 4,833
  • 5
  • 38
  • 68
  • I need to force the orientation – Curio Jan 01 '17 at 18:48
  • I was in a similar situation where I wanted the screen to be in portrait during an AsyncTask. I struggled to not keep it from crashing. I finally just locked the screen in its existing state with the method above. I suggest you force the orientatin before even getting to the activity with the AsyncTask... perhaps with an intent. Good Luck. – seekingStillness Jan 01 '17 at 19:14
  • I need to change the orientation only for two fragments. Look at the question which I updated. I solved the crash problem – Curio Jan 01 '17 at 20:31