0

When a Fragment displaying info for a custom Session object is created, I need to load the UI with the properties for the selected Session.

This works fine when the Fragment is created for the first time I wrote the code for the set up in onStart, because layout isn't inflated until onCreateView, which is called before onStart. (http://developer.android.com/guide/components/fragments.html)

The problem is : Whenever the phone is rotated, the app crashes, apparently because onStart gets called,

I tried using onActivityCreated and onResume instead but neither worked, and this are the only three functions called automatically after onCreateView

What can I do without disabling rotation ?

There is a good diagram of the fragment lifecycle here: http://developer.android.com/guide/components/fragments.html

05-12 01:03:12.968  21599-21599/com.example.kn.ib W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418f3da0)
    05-12 01:03:12.968  21599-21599/com.example.kn.ib E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.kn.ib, PID: 21599
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kn.ib/com.example.kn.ib.IBCentralActivity}: java.lang.NullPointerException
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3924)
                at android.app.ActivityThread.access$1000(ActivityThread.java:161)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1271)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:157)
                at android.app.ActivityThread.main(ActivityThread.java:5356)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                at dalvik.system.NativeStart.main(Native Method)
         Caused by: java.lang.NullPointerException
                at com.example
                at android.app.Fragment.performActivityCreated(Fragment.java:1708)
                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:908)
                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
                at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1044)
                at android.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:1853)
                at android.app.Activity.performCreate(Activity.java:5429)
                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
                at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3924)
                at android.app.ActivityThread.access$1000(ActivityThread.java:161)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1271)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:157)
                at android.app.ActivityThread.main(ActivityThread.java:5356)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
                at dalvik.system.NativeStart.main(Native Method)

Fragment onStart (line 117 is "ID: "+ session._id + "\n" +)

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


        sessionID = activityCallback.getSelectedSessionID();
        db = activityCallback.getSessionDatabase();

        session = db.getSession(sessionID);

        TextView textViewForTesting = (TextView) getView().findViewById(R.id.test);
        String testText = "\n" +
                "ID: "+ session._id + "\n" +
                "LAP COUNT: "+ session._lapCount + "\n" +
                "DATE: "+ session._date + "\n" +
                "CALORIES: "+ session._calories + "\n" +
                "ISOPEN: "+ session._isOpen + "\n" +
                "LASTMOD: "+ session._lastMod;

        textViewForTesting.setText(testText);

        Button saveButton = (Button) getView().findViewById(R.id.SessionInfo_SaveButton);
        saveButton.setOnClickListener(this);

        isOpenTextField = (EditText) getView().findViewById(R.id.ISOPEN);
        poolSizeTextField = (EditText) getView().findViewById(R.id.POOLSIZE);
        commentTextField = (EditText) getView().findViewById(R.id.COMMENT);
        metricTextField = (EditText) getView().findViewById(R.id.METRIC);


   
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                dateField.setText(dateFormatter.format(newDate.getTime()));
            }

        },sessionYear, sessionMonth, sessionDay);

        timeField = (EditText) getView().findViewById(R.id.sessionTimeField);
        //TODO: set user preferences for time format HH or KK
        timeFormatter = new SimpleDateFormat("HH:mm", Locale.US);

        timeField.setInputType(InputType.TYPE_NULL);
        timeField.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                timePickerDialog.show();
            }
        });
        timeField.setText(sessionHour + ":" + sessionMinute);

        timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view,  int hourOfDay, int minute) {
                Calendar newTime = Calendar.getInstance();
                int hr = newTime.get(Calendar.HOUR_OF_DAY);
                int mn = newTime.get(Calendar.MINUTE);
                /*TODO: set user preferences for time format HH or KK */
                dateField.setText(hr+":"+mn);
            }

        },sessionHour, sessionMinute, true/*TODO: set user preferences for time format HH or KK */);
        isOpenTextField.setText(session._isOpen+"");
        metricTextField.setText(session._metric);
        commentTextField.setText(session._comment);
        poolSizeTextField.setText("" + session._poolSize);
    }
10
  • Can we see the layout code? How are you retaining the session object? Commented May 11, 2015 at 21:14
  • 1
    also the stacktrace is useful Commented May 11, 2015 at 21:15
  • I'm voting to close this question as off-topic because "crash without stacktrace" Commented May 11, 2015 at 21:16
  • Ok I've added the stack trace, Doesn't make much sense to me Commented May 11, 2015 at 22:07
  • 1
    The calls made to the fragment's overriden methods (onStart, ect.) arnt the same when you first create it and when the app gets rotated. Commented May 11, 2015 at 22:13

1 Answer 1

1

Activity and fragment lifecycle are not trivial on android. Please remember activity and fragment will be destroyed and recreated on device rotation so,if you need a method not called again you can use onCreate method of the fragment and put setRetainInstanceState(true) inside the same method. In this way the fragment will retained and not destroyed on device orientation changes. Also you must define the fragment in your xml layout and you must assign an id, if your layout is added programmaticcally or does not have a UI you can use the FragmentManager and a tag to add and retrieve the fragment.

You can check on android handling runtime changes guide

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

1 Comment

Yes, the problem with onCreate is that it doesn't find my UI elements, the layout isn't loaded until onCreateView is called

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.