Android:保存对象onPause()和读取对象onResume()

时间:2013-09-04 19:28:11

标签: java android

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

我的应用程序的过程是保存对象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;
  }

2 个答案:

答案 0 :(得分:0)

在@override上总是分别出现super.onPause()和super.onResume(),然后才能放置你的代码。

答案 1 :(得分:0)

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

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

  private Customer read() {
     ...
     fileInputStream.close()
  }