简体   繁体   English

方向改变后片段变为空

[英]Fragments gets null after orientation change

I am having troubles with my Fragments . 我的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. 我有我的“BiegestatusFragment”改为横向 ,还有我打电话这是条形码扫描的方法,对意图的结果我设置的参数在我的片段。

Here is my Barcode-Scanning Activity 这是我的条形码扫描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 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. 现在,由于方向更改,我的Fragment为空。 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) 

您可以通过将清单中的以下行添加到活动代码中,来在更改方向后强制不重新加载活动

android:configChanges="orientation" 
 //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();
    }

Inside fragment ,in onCreateView() try using : 在片段内部,在onCreateView()中尝试使用:

setRetainInstance(true);

Check the doc here : https://developer.android.com/reference/android/app/Fragment#setRetainInstance(boolean) 在此处检查文档: https : //developer.android.com/reference/android/app/Fragment#setRetainInstance(boolean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM