Rendering problem in Android Studio when writing files

Daltrey Waters :

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?

CommonsWare :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403753&siteId=1