【发布时间】:2016-09-28 20:16:36
【问题描述】:
我已经尝试了几十个教程和指南,并在 stackoverflow 和其他网站上尝试让它正常工作。有问题的应用程序有一个自定义类,其中包含一个列表,其中包含有列表的项目。理想情况下,我希望能够在其他活动关闭或暂停时进行保存。我遇到的问题是,当我关闭另一个活动(按后退按钮)时,它会显示保存消息的日志。但是当我打开它而不是加载它应该保存的信息时,它会显示一个空白列表。这是我的代码:
这是引用自定义类并可以调用保存和加载方法的主要活动:
public class ReminderList extends AppCompatActivity {
public static ListHolder Lholder;
public static ArrayList<ReminderType> AllReminders=new ArrayList<>();
public reminderCAdapter adapter;
public static ReminderType currentReminderType;
public static ItemType currentItemType;
public static TimeType currentTimesType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_list);
//generate list
File file=new File("f.rem");
if(file.exists()) {
try {
LoadData();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
AllReminders=Lholder.Rlist;
}
adapter=new reminderCAdapter(AllReminders,this);
ReminderType r1=new ReminderType("Thing1");
//AllReminders.add(r1);
ReminderType r2=new ReminderType("Thing2");
//AllReminders.add(r2);
//instantiate custom adapter
//MyCustomAdapter adapter = new MyCustomAdapter(AllReminders, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.listView);
lView.setAdapter(adapter);
}
public void onResume(){
super.onResume();
adapter.notifyDataSetChanged();
}
public static void SaveData() throws IOException {
Log.e("Saving Data", "trying");
FileOutputStream fos=new FileOutputStream("f.rem");
ObjectOutputStream oos= new ObjectOutputStream(fos);
oos.writeObject(Lholder);
oos.close();
}
public void LoadData() throws IOException, ClassNotFoundException {
Log.e("Loading Data", "trying");
FileInputStream fis=new FileInputStream("f.rem");
ObjectInputStream ois=new ObjectInputStream(fis);
Lholder=(ListHolder) ois.readObject();
ois.close();
}
public void AddToList(View view){
Intent intent = new Intent(this,ReminderSettings.class);
intent.putExtra("Type", "new");
startActivity(intent);
}
}
另一个活动像这样调用保存函数:
@Override
protected void onStop() {
super.onStop(); // Always call the superclass method first
try {
ReminderList.SaveData();
} catch (IOException e) {
e.printStackTrace();
}
}
这是我尝试过的最新帖子的小列表:
How to create a file on Android Internal Storage?
如果有人能帮助我理解为什么这不起作用或我需要做什么,我将不胜感激。
非常感谢
【问题讨论】:
-
it crashes-> 堆栈跟踪? -
请发布堆栈跟踪,以便我们为您提供帮助。
-
我的错。当我有 fos=openFileOutput("f.rem", this.MODE_PRIVATE); 时它崩溃了现在它似乎什么也没做。两条日志消息都显示在日志中,但如果我关闭应用程序并重新打开它,则不会加载任何内容。很抱歉混淆了。
标签: java android file-io saving-data