在使用Android Studio编写文件时的渲染问题

huangapple go评论81阅读模式
英文:

Rendering problem in Android Studio when writing files

问题

我有一个非常简单的代码,像这样写入文件 -

    val path = context.getExternalFilesDir(null)?.absolutePath + "/user_id"
    var file = File(path)
    file.writeText("user id")

这在模拟器上可以正常工作。

然而,当我在Android Studio上编辑这个代码时,我正在使用的layout.xml的渲染(调用上面的代码)失败了,引用了`file.writeText`代码行上的错误。

更具体地说,我在调用堆栈上得到了这个异常 -

    java.io.FileNotFoundException: null\user_id(系统找不到指定的路径)

换句话说,上面的代码在模拟器中可以正常工作,但在Android Studio布局预览中却无法正常工作。

有人对这个问题有什么想法吗?
英文:

I have a very simple code that writes to a file like this -

val path = context.getExternalFilesDir(null)?.absolutePath + "/user_id"
var file = File(path)
file.writeText("user id")

This works without a problem on emulator.

However, when i'm editing this on Android Studio, the rendering of the layout.xml I'm using (that invokes the code above) fails, citing an error on the file.writeText code line

More specifically, I get this exception on the callstack -

java.io.FileNotFoundException: null\user_id (The system cannot find the path specified)

So in other words, the code above works well in emulator, but not inside Android Studio layout preview.

Anyone has any thoughts on this item?

答案1

得分: 1

布局预览正在渲染视图。我能想到的唯一原因是这段代码在 Android Studio 的布局预览中运行,可能是因为:

  • 你编写了一个自定义视图(这没问题),并且

  • 那个自定义视图试图进行磁盘 I/O 操作(这是不合适的)

因此,最好的解决方案是将磁盘 I/O 操作移到更合适的地方(例如,存储库对象)。

如果你确定要保持代码原来的位置,在代码周围包裹一个 isInEditMode() 的检查条件,并且如果在编辑模式下则不进行 I/O 操作。这意味着代码正在 IDE 中运行,Context 上的许多功能,比如 getExternalFilesDir(),将无法正常工作。

英文:

The layout preview is rendering views. The only reason I can think of why this code would be running in the Android Studio layout preview is because:

  • You wrote a custom view (which is fine), and

  • That custom view is trying to do disk I/O (which is not fine)

So, the best solution is to move the disk I/O to something more appropriate (e.g., a repository object).

If you are sure that you want to keep that code where it is, wrap it in a check for isInEditMode() and do not do the I/O if you are in edit mode. That means the code is running in an IDE, and many things on Context, such as getExternalFilesDir(), will not work.

huangapple
  • 本文由 发表于 2020年4月4日 07:49:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/61022047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定