0

I am having troubles with my Fragments. I have four fragments which were in portrait mode.

Setting the fragments

public void setCorrectNavigationItem(int id) {
    if (id == R.id.nav_auftragsbilder) {
        fragment = new AuftragsbilderFragment();
        id = R.id.nav_auftragsbilder;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else if (id == R.id.nav_auftragskorrektur) {
        fragment = new AuftragskorrekturFragment();
        id = R.id.nav_auftragskorrektur;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else if (id == R.id.nav_lagerplatz) {
        fragment = new LagerplatzFragment();
        id = R.id.nav_lagerplatz;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else if (id == R.id.nav_biegenstatus) {
        fragment = new BiegestatusFragment();
        id = R.id.nav_biegenstatus;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
    _navigationView.setCheckedItem(id);
    _selectedMenuItem = id;

    SharedPreferences.Editor editor = menuCheck.edit();
    editor.putInt("id", id);
    editor.commit();

    //Fragment öffnen
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.fragment_container, fragment);
        ft.commit();
    }
}

So in my fragment setting method I now have to set the orientation for each different fragment. I had to change my 'BiegestatusFragment' to landscape, there I am calling a method which is scanning barcodes, on intent result I set parameters in my Fragment.

Here is my Barcode-Scanning Activity

//Biegestatus Begleitschein-Barcodes
public void makeBiegestatusBegleitscheinBarcode() {
    _lastAction = ACTION_BIEGESTATUS_BEGLEITSCHEIN_BARCODE;
    if (!checkCameraPermission(this, PERMISSIONS)) {
        ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
    } else {
        Intent intent = new Intent(this, ContinuousCaptureActivity.class);
        startActivityForResult(intent, 1);
    }
}

Intent Result

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        ArrayList<String> begleitscheine = data.getStringArrayListExtra("begleitscheine");
        if (resultCode == 1 && begleitscheine != null) {
            //HERE IT IS NULL
            ((BiegestatusFragment) fragment).setBegleitscheine(begleitscheine);
        } else {
            Toast.makeText(this, "Scannen abgebrochen", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, "Unbekannter Fehler aufgetreten, Entwickler kontaktieren.", Toast.LENGTH_LONG).show();
    }
}

Fragments onCreateView

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_biegestatus, container, false);

    _cardEdit = (EditText) v.findViewById(R.id.workerEdit);
    _scrollViewArticles = (ScrollView) v.findViewById(R.id.scrollViewArticles);
    _searchImageLayout = (LinearLayout) v.findViewById(R.id.searchImageLayout);
    _personalNummer = (EditText) v.findViewById(R.id.workerEdit);
    _progressBar = (LinearLayout) v.findViewById(R.id.progressBar);
    _maschinenPicker = (NumberPicker) v.findViewById(R.id.maschinenPicker);
    _pickerHolder = (LinearLayout) v.findViewById(R.id.pickerHolder);
    _scanBegleitscheinBtn = (Button) v.findViewById(R.id.scanBegleitscheinBtn);

    return v;
}

Method should be called

public void setBegleitscheine(ArrayList<String> begleitscheine) {
    _begleitscheine = begleitscheine;
}

Now my Fragment is null because of the orientation change. Removing the orientation setting methods solves my problem. But I need to have this fragment in landscape.

Error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: at.co.era.bilder.erabilderapp, PID: 21835
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=1, data=Intent {  launchParam=MultiScreenLaunchParams { mDisplayId=0 mBaseDisplayId=0 mFlags=0 }(has extras) }} to activity {at.co.era.bilder.erabilderapp/at.co.era.bilder.erabilderapp.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void at.co.era.bilder.erabilderapp.BiegestatusFragment.setBegleitscheine(java.util.ArrayList)' on a null object reference
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4520)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563)
                      at android.app.ActivityThread.-wrap22(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void at.co.era.bilder.erabilderapp.BiegestatusFragment.setBegleitscheine(java.util.ArrayList)' on a null object reference
                      at at.co.era.bilder.erabilderapp.HomeActivity.onActivityResult(HomeActivity.java:1130)
                      at android.app.Activity.dispatchActivityResult(Activity.java:7280)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4516)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4563) 
                      at android.app.ActivityThread.-wrap22(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1698) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6776) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
Damaro
  • 55
  • 1
  • 8
  • 1
    The prefered way to instantiate fragments is through **newInstance**. Take a look at [this](https://stackoverflow.com/questions/9245408/best-practice-for-instantiating-a-new-android-fragment#) – Evgeni Enchev Jan 17 '19 at 07:26
  • Changed it to newInstance...But when calling the method of id says my `_maschinenPicker` is null String maschine = _maschinen.get(_maschinenPicker.getValue()); – Damaro Jan 17 '19 at 07:36

3 Answers3

1
 //Fragment öffnen
    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.replace(R.id.fragment_container, fragment);
        ft.addToBackStack(null); // or you can give it any name instead of null to get the frament when poping the fragment from backstack
        ft.commit();
    }
Khurram Shahzad
  • 162
  • 2
  • 12
0

You can force your activity not to reload after orientation changed by adding the following line in manifest to your activity tag

android:configChanges="orientation" 
Khurram Shahzad
  • 162
  • 2
  • 12
  • thanks for you answer...I have added it long time ago, but still having this problem. – Damaro Jan 17 '19 at 07:38
  • Please add your fragment to backstack by doing addToBackStack("withSomeName") Added in API level 11 Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack. – Khurram Shahzad Jan 17 '19 at 08:10
  • How to do this? – Damaro Jan 17 '19 at 08:34
  • this is not a good idea to force your activity not to be recreated when an orientation charges,its needs to created in order to use layouts ,res for different orientations – Ajay Chauhan Jan 17 '19 at 08:56
  • @AjayChauhan I am using just portrait mode...Only for the single fragment I need landscape. – Damaro Jan 17 '19 at 09:10
0

Inside fragment ,in onCreateView() try using :

setRetainInstance(true);

Check the doc here : https://developer.android.com/reference/android/app/Fragment#setRetainInstance(boolean)

Ajay Chauhan
  • 1,471
  • 4
  • 17
  • 37