简体   繁体   English

写入文件时 Android Studio 中的渲染问题

[英]Rendering problem in Android Studio when writing files

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但是,当我在 Android Studio 上编辑它时,我正在使用的 layout.xml 的渲染(调用上面的代码)失败,引用file.writeText代码行上的错误

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.换句话说,上面的代码在模拟器中运行良好,但在 Android Studio 布局预览中却不行。

Anyone has any thoughts on this item?有人对这个项目有任何想法吗?

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:我能想到为什么这段代码会在 Android Studio 布局预览中运行的唯一原因是:

  • You wrote a custom view (which is fine), and您编写了一个自定义视图(这很好),并且

  • That custom view is trying to do disk I/O (which is not fine)该自定义视图正在尝试执行磁盘 I/O(这不好)

So, the best solution is to move the disk I/O to something more appropriate (eg, a repository object).因此,最好的解决方案是将磁盘 I/O 移动到更合适的位置(例如,存储库对象)。

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.如果您确定要保留该代码,请将其包装在isInEditMode()的检查中,并且如果您处于编辑模式,则不要执行 I/O。 That means the code is running in an IDE, and many things on Context , such as getExternalFilesDir() , will not work.这意味着代码在 IDE 中运行,并且Context上的许多东西,例如getExternalFilesDir() ,将不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM