gpt4 book ai didi

java - 将 saveInstanceState 与 Uri ArrayList 和适配器一起使用

转载 作者:行者123 更新时间:2023-11-29 23:45:34 25 4
gpt4 key购买 nike

我创建了一个 ListView ,用于将文件从 SD 卡上传到列表并将其附加到列表中。然而我退出了 Activity 并且 onDestroyed 被调用并且我从我的 listView 中丢失了所有数据。我正在使用 ArrayList FileUploaded 和适配器来上传文件,但我对如何在“onSavedInstanceState”方法上实现它感到困惑。

我已进行研究,但仍有一些问题。

我是否存放了错误的元素?

请帮助...任何建议。

我的变量:

ListView Added_Files;
Button Select_File;
Button Add_To_List;
Button Save_Button;
Button Add_To_DropBox;
TextView selectedFile;
MediaPlayer mediaPlayer;
ArrayList<Uri> FileUpload = new ArrayList<Uri>();
ArrayAdapter adapter;

//单击“上传到列表”按钮时将文件添加到 ListView 的方法

 public void addList(){

adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,FileUpload);
Add_To_List.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Added_Files.setAdapter(adapter);
adapter.add(uri.getPath());
((BaseAdapter) Added_Files.getAdapter()).notifyDataSetChanged();
selectedFile.setText("");
Make_File_Empty();

// Toast.makeText(AddFiles.this, "File Added", Toast.LENGTH_SHORT).show();
}
});

}

这里是选择sd卡上的文件并显示在屏幕上的方法

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
//If file selection was successfull
if (resultCode == RESULT_OK) {
if (data != null) {
//get uri of the selected file
uri = data.getData();

Log.i(TAG, "Uri = " + uri.toString());
try {
//get file path from Uri
// Toast.makeText(AddFiles.this, "File Selected: " + uri.getPath(), Toast.LENGTH_SHORT).show();
selectedFile.setText("Selected File: " + uri.getPath());

addList();

} catch (Exception e) {
Log.e("FileSelectorActivity", "File select error", e);
}
super.onActivityResult(requestCode, resultCode, data);
}
}
}
}

最后,onSaved/restore 方法:

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putStringArrayList("key",FileUpload );
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
FileUpload = savedInstanceState.getStringArrayList("key");
}

最佳答案

仔细看这篇文章:https://developer.android.com/guide/components/activities/activity-lifecycle#save-simple-lightweight-ui-state-using-onsaveinstancestate

onSaveInstanceState 中,您似乎在调用 super 后保存状态,这可能会导致数据无法保存。您可能还想保存和恢复 TextView 中的文本,以便在恢复 UI 时显示。

另一件需要注意的是这里所说的:注意:当用户明确关闭 Activity 时或在其他情况下调用 finish() 时,不会调用 onSaveInstanceState()。

保存状态只是为了在短期情况下保存数据(示例在调用 super 之前保存它),如果你想保存更长时间(在应用程序启动之间)你可能想要使用一个 SQLite 数据库,它有很多更复杂。

我不是这方面的专家,但希望这对您有所帮助!我建议在 onSaveInstanceStateonRestoreInstanceState 中设置断点,以查看在遇到问题时调用的内容。

关于java - 将 saveInstanceState 与 Uri ArrayList 和适配器一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com