有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android:在Pause()上保存对象,在Resume()上读取对象

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

我的应用程序的过程是在Pause()上保存对象并在Resume()上获取对象

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
        安卓:name=".ActivityA"
        安卓:configChanges="orientation|keyboardHidden|screenSize"
        安卓:label="@string/app_name"
        >
    </activity>
    <activity
        安卓:name=".ActivityB"
        安卓:configChanges="orientation|keyboardHidden|screenSize"
        安卓:label="@string/app_name" >
    </activity>

在此处保存和读取对象(活动A):

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) 个答案

  1. # 1 楼答案

    在@override上总是超级的。onPause()和super。onResume()分别位于第一位,然后只有您可以放置代码

  2. # 2 楼答案

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

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