繁体   English   中英

为什么我保存的片段总是为空?

[英]Why does my saved fragment is always null?

我正在尝试在我的应用程序中保存我的片段实例(至少我想保存模型实例)。 我有一个底部导航活动,这个片段从一个 ble 设备获取了一系列数据。 我想给用户机会,以便在接收数据时在片段中导航。 我可以做到,但是当我回到获取片段时,它会创建另一个获取数据的对象实例,因此我失去了对当前正在工作的对象的控制。 所以我想保存片段实例。 我尝试了thisandroid开发人员描述中的所有答案。 正如您在此处的代码中所见,我现在只保存一个布尔值以尝试它是否有效。

@Override
public void onSaveInstanceState(@NonNull Bundle saved) {
    // call superclass to save any view hierarchy

    out.println("Saving...");
    out.println(start);
    if (!start)
    {
        /*Gson gson = new Gson();
        String json= gson.toJson(model);
        out.println(json);
        outState.putString("MODEL", json);*/
        saved.putBoolean("START", start);
    }
    super.onSaveInstanceState(saved);


}

无论如何,当我更改片段时没有任何反应,但我可以保存它在 onDestroy 回调中调用此函数。

    @Override
public void onDestroyView()
{
    super.onDestroyView();
    Bundle saved = new Bundle();
    this.onSaveInstanceState(saved);
    model.stop();
    model.disconnect();
    out.println("Destroy yourself");

}

但是在 onCreateView 和 onCreate 中,我的包仍然为空。 我不明白为什么。

    @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    out.println(savedInstanceState);
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        start = savedInstanceState.getBoolean("START");
        out.println(start);
    } else {
        start = false;
    }
}

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    out.println(savedInstanceState);
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        start = savedInstanceState.getBoolean("START");
        out.println(start);
    } else {
        start = false;
    }
    model = new ViewModelProvider(this).get(AcquisitionModel.class);


    model.getFreq().observe(getViewLifecycleOwner(), freq -> {
        updateFreq(freq);
    });
    model.getOrder().observe(getViewLifecycleOwner(), order -> {
        updateOrder(order);
    });
    model.getToDrawn().observe(getViewLifecycleOwner(),  toDrown-> {
        draw(toDrown);
    });
    View root = inflater.inflate(R.layout.fragment_acquisition, container, false);

    graph = (GraphView) root.findViewById(R.id.line_graph);
    graph.getViewport().setXAxisBoundsManual(true);
    GridLabelRenderer gridLabel = graph.getGridLabelRenderer();
    //gridLabel.setPadding(64);
    util = new AppUtilis(this.getContext());
    //graph.getViewport().setMaxX(5);

    series = new LineGraphSeries<>();
    graph.getViewport().setScalable(true);
    graph.getViewport().setScrollable(true);
    //series.setThickness(3);

    graph.addSeries(series);

    text= root.findViewById(R.id.frequenza);
    RG = (RadioGroup) root.findViewById(R.id.RG);
    RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected

            String nonso = "";
            if (checkedId== R.id.ecg_switch) {
                TextView text= (TextView) root.findViewById(R.id.label);
                text.setText("Frequenza cardiaca (BPM)");
                nonso = "ecg";
            }
            else
            {
                TextView text= (TextView) root.findViewById(R.id.label);
                text.setText("Frequenza respiratoria");
                nonso = "resp";
            }
            model.scambio(nonso);
        }
    });

    B_start= (Button) root.findViewById(R.id.start_stop);
    B_start.setOnClickListener(new View.OnClickListener()
    { //utente pigia il bottone

        @Override

        public void onClick(View v) {

            //controllo se esiste il dispositivo
            if (model.isConnected() || disp != null) {
                boolean ans;
                if (start) {
                    ans = model.stop();
                    if (ans) {
                        start = false;//chiama lo stop
                        B_start.setText("Start");

                        //set colore standard
                        B_start.setBackgroundColor(Color.rgb(3, 218, 197));
                    }
                } else {
                    ans = model.start();
                    if (ans) {
                        start = true;
                        graph.removeAllSeries();
                        series = new LineGraphSeries<>();
                        series.setThickness(3);
                        graph2LastXValue = 0d;
                        graph.addSeries(series);
                        B_start.setText("Stop");
                        B_start.setBackgroundColor(Color.rgb(255, 0, 0));
                    }
                }
            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }

        }

    });
    B_export = (Button) root.findViewById(R.id.exp);
    B_export.setOnClickListener(new View.OnClickListener()
    { //utente pigia il bottone
        @Override

        public void onClick(View v) {
            Log.d("saving", "premuto");
            if (model.isConnected() || disp != null) {


                util.loading("Sto salvando", false);
                model.stop();
                start = false;//chiama lo stop
                B_start.setText("Start");
                B_start.setBackgroundColor(Color.rgb(3, 218, 197));

                boolean ans = model.saveAll();
                analyzeCough(model.getResp().getFile(), model.fc);

                util.loadingFinished();
                if (ans)
                {
                    util.alert("Successo", "Esportazione avvenuta! Cerca nella cartella Registrazioni nella memoria interna del telefono");
                }
                else {
                    util.alert("Errore", "Esportazione fallita");
                }

            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }
        }
    });
    share = root.findViewById(R.id.share);
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (model.isConnected() || disp != null) {
                //funzione per condividere i file
                //controllo se non sia già stato fatto un export
                util.loading("Sto salvando", false);
                //model.disconnect();
                start = false;//chiama lo stop
                B_start.setText("Start");
                B_start.setBackgroundColor(Color.rgb(3, 218, 197));
                model.stop();
                boolean ansi = model.saveAll();
                analyzeCough(model.getResp().getFile(), model.fc);
                ArrayList<File> fil = model.getAllFiles();
                util.loadingFinished();
                if (ansi) {
                    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                    StrictMode.setVmPolicy(builder.build());
                    //provo la condivisione
                    //prendi i path con una funzione dal model
                    try {
                        Intent sharingIntent = new Intent();
                        sharingIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files.");
                        sharingIntent.setType("text/*");
                        ArrayList<Uri> files = new ArrayList<Uri>();
                        for (int i = 0; i < fil.size(); i++) {
                            files.add(Uri.fromFile(fil.get(i)));
                        }
                        sharingIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
                        startActivity(Intent.createChooser(sharingIntent, "Condividi con"));
                        out.println("Post sharing");
                    } catch (Exception e) {
                        e.printStackTrace();
                        util.alert("Errore", "Condivisione fallita!");
                    }

                } else {
                    util.alert("Errore", "Condivisione fallita");
                }
            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }

        }
    });
    return root;
}

我还尝试从某人提到的活动中保存片段作为我之前发布的链接中的答案,但它也不起作用。 有人有什么想法吗? 提前致谢。

编辑这是我在活动中的 onCreate

    @Override
protected void onCreate(Bundle savedInstanceState) {
    model = new ViewModelProvider(this).get(ConnectionViewModel.class);
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET},
            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
        // solo funzioni nuove e solo se non è già stato accettato
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }
    try {
        setTheme(R.style.splashScreenTheme);
        super.onCreate(savedInstanceState);
        sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    setTheme(R.style.Theme_Ble);
    setContentView(R.layout.activity_main3);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.tosse, R.id.grafici, R.id.elettrodi)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

    util = new AppUtilis(this);
    NavigationUI.setupWithNavController(navView, navController);
    Button easter;
    easter = (Button) findViewById(R.id.easterEgg);
    easter.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            System.out.println("uovooooo");
            Intent intent = new Intent(util.getContext(), SettingsActivity.class);
            System.out.println("Vado a cercare roba");
            startActivityForResult(intent, 3);

        }
    });
    Ble = (ImageButton) findViewById(R.id.IconaBle);
    Ble.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            final BluetoothManager bluetoothManager =
                    (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();


            // Ensures Bluetooth is available on the device and it is enabled. If not,
            // displays a dialog requesting user permission to enable Bluetooth.
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled() ||  !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
                /*
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);*/
                util.alert("GPS e Bluetooth", "Per trovare dispositivi devi attivare GPS e Bluetooth");
            }
            else
            {
                Intent intent = new Intent(util.getContext(), BleScan.class);
                System.out.println("Vado a cercare roba");
                startActivityForResult(intent, 2);
            }

        }
    });

}

如果您在onDestoryView()保存任何数据,则意味着应用程序已关闭。 除非系统自行强制关闭,否则savedInstanceState不会在应用程序关闭后savedInstanceState存在。 因此,即使您保存了实例, onCreate()也会打印 null。 加上onDestroyView()并不一定总是被调用。 有时 os 不会调用onDestroyView() 如果用户没有离开应用程序并且您正在加载保存的实例,您应该尝试将对象保存在onPause()onStop()

暂无
暂无

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

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