【问题标题】:Android XML internal storageAndroid XML 内部存储
【发布时间】:2014-12-20 14:12:23
【问题描述】:

我正在尝试使用 android 中的 XML 保存一些数据以保存到设备内部存储中。

我想确保应用程序是按照 打开/关闭 和 单一责任 原则编写的。 (所以我可以轻松地在存储方法之间切换)

-domain
|---db
|---|---appReader
|---|---|---AppReader.java
|---|---|---XMLAppReader.java
|---|---appWriter
|---|---|---AppWriter.java
|---|---|---XMLAppWriter.java   
|---DBFacade.java
|---DBFacadeImpl.java
-MainActivity.java

这是我目前的结构,...

我现在面临的问题是,在每个关于 android 和 xml 的教程中,他们都使用函数 openFileOutput(filename,Context.Mode_Append) 我猜这是来自 Activity 超类的函数?

我将如何初始化我的FileOutputStream 并仍然保持我的打开/关闭和单一责任原则完好无损?

我应该将一个 Activity 实例传递给我的 XMLAppWriter 构造函数吗? 这不会破坏单一职责原则吗?

【问题讨论】:

  • “我现在面临的问题是,在每个关于 android 和 xml 的教程中,他们都使用函数 openFileOutput(filename,Context.Mode_Append)”——当然不是每个教程。 “我猜这是来自 Activity 超类的函数?” -- openFileOutput()是Context上的一个方法,Activity继承自Context。 getFilesDir() 是 Context 上的另一种方法,它返回一个 File 对象,该对象指向您可以为应用程序的主要内部存储部分读取和写入文件的位置。
  • 所以你是说我可以在我的 XMLWriter 构造函数中添加一个 Context 参数?
  • 我不知道。在地球上约 70 亿人中,您是唯一一个知道您的 XMLWriter 是什么、正在使用它、它向使用它的人公开了什么 API 等的人。
  • 呃,这个名字不言自明。它使用 XML 来保存数据(写入存储)。我的问题清楚地说明了问题。我需要使用函数“openFileOutput(..)”,它是“上下文”上的一种方法。我的 XMLWriter 是一个现有的类,它只实现 AppWriter 也不扩展任何其他类。那么添加 Context 参数不会破坏 SRP 吗?
  • “这个名字是不言自明的”——是的,但是这个名字没有记录实现或者它的使用。 “我需要使用函数 'openFileOutput(..)',它是 'Context' 上的一个方法”——不,您需要 XMLWriter 才能编写 XML。这并不一定意味着使用openFileOutput(),也不意味着XMLWriter 必须是调用openFileOutput() 或getFilesDir() 的人。 “那么添加上下文参数不会破坏 SRP 吗?” -- 恕我直言,不会超过File、String 或boolean 参数。

标签: java android xml single-responsibility-principle open-closed-principle


【解决方案1】:

您可以使用应用程序的上下文方法代替传递活动实例作为参数,这不违反单一责任原则。

getApplicationContext().openFileOutput(name, mode);

【讨论】:

  • 这对我一点帮助都没有,要使用 'getApplicationContext()' 我需要从扩展 Activity 类的类中调用它。
  • 您可以扩展android Application 类,public YourApp extends Application { //... },并在YourApp 中使用getApplicationContext() 进行初始化。但是您还需要在清单文件中指定应用程序名称。
  • 所以在XMLAppWriter 的构造函数中(我需要使用openFileOutput(...) 方法的类)我需要调用getApplicationContext?
  • 是的,将getApplicationContext()的结果作为XMLAppWriter构造函数的参数传递。 XMLAppWriter(Context context),然后是 context.openFileOutput(...)
猜你喜欢
  • 2013-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-12
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
相关资源
最近更新 更多