0

我无法将对象(自定义)保存到文件中。

我的应用程序的过程是保存对象 onPause() 并获取对象 onResume()。

1) I have two activities (Activity A and Activity B)
2) I am saving and reading the object in Activity A 
3) Activity A call Activity B on Button click.

以下是复制我的问题的步骤:(活动 A 通过从文件中读取对象来启动。)

1) Click on button on Activity A.
2) Save custom object to file in onPause method of Activity A.
3) Activity B launches
4) Click on Action bar back button.
5) Read the object from file saved in onResume() method of Activity A.
6) Again click on the button on Activity A.
7) Saves custom object to file in onPause() method of Activity A.
8) Activity B launches.
9) Click on back button of device.
10) Tries to read the object from file in onResume() method of Activity A.

请注意:我正在保存和读取的文件位于同一位置。

在第 10 步,读取的对象不正确。我怀疑是在第 7 步,对象未正确保存。

有人可以帮助将对象保存到文件并将文件读取到对象吗?

如果我错了,请纠正我。根据 Android 文档,onSaveInstanceState() 和 onRestoreInstanceState() 不是合适的保存方法。

这是清单:

    <activity
        android:name=".ActivityA"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        >
    </activity>
    <activity
        android:name=".ActivityB"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name" >
    </activity>

在此处保存和读取对象(ActivityA):

Customer customer;
@Override
protected void onPause() {
    super.onPause();
    save(customer);
}

@Override
protected void onResume() {
    super.onResume();
    customer = read();
}

  private void save(Customer customer) {
    try {
        FileOutputStream fileOutputStream = openFileOutput("Customer.properties", Context.MODE_PRIVATE);
        Properties properties = new Properties();
        properties.put("CUSTOMER_NAME", customer.getName());
        properties.put("CUSTOMER_ID", customer.getId());
        properties.put("CUSTOMER_PLACE", customer.getPlace());

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

     private Customer read() {
     try {
          FileInputStream fileInputStream = openFileInput("customer.properties");
          Properties properties = new Properties();
          properties.load(fileInputStream);
          Customer customer = new Customer();
          customer.setName(properties.get("CUSTOMER_NAME"));
          customer.setId(properties.get("CUSTOMER_ID"));
          customer.setPlace(properties.get("CUSTOMER_PLACE"));
          return customer;
     } catch(Exception e) {
     }
   return null;
  }
4

2 回答 2

0

完成后应该关闭输入和输出流,否则会遇到并发问题

  private void save(Customer customer) {
     ...
     fileOutputStream.close()
  }

  private Customer read() {
     ...
     fileInputStream.close()
  }
于 2013-09-04T20:18:26.297 回答
0

在@override 上,super.onPause() 和 super.onResume() 总是先出现,然后只有你可以放置你的代码。

于 2013-09-04T19:45:32.590 回答