我正在尝试在我的应用程序中保存我的片段示例(至少我想保存模型示例)。我有一个底部导航活动,这个片段从一个可编程设备获取一系列数据。我想让用户有机会在接收数据时在片段中导航。我可以做到,但当我回到采集片段时,它会创建另一个获取数据的对象示例,因此我无法控制当前正在工作的对象。所以我想保存片段示例。我尝试了这个和android开发者描述中的每一个答案。正如您可以从我的代码中看到的,我现在只保存一个布尔值,以尝试它是否有效。
@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 in活动
@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);
}
}
});
}
1条答案
按热度按时间j2datikz1#
如果您将任何数据保存在
onDestoryView()
这意味着应用程序已关闭。及savedInstanceState
除非系统自身强制关闭应用程序,否则应用程序无法关闭。所以onCreate()
即使您保存了示例,也将打印null。加上onDestroyView()
不必总是打电话。有时操作系统不调用onDestroyView()
. 您应该尝试将对象保存在内部onPause()
或onStop()
如果用户没有离开应用程序,而您正在加载保存的示例。