- android studio put itself into read only mode for all files #2994
- Comments
- james-lawrence commented Dec 23, 2018
- Steps to Reproduce
- Version info
- pq commented Dec 25, 2018 •
- james-lawrence commented Dec 25, 2018
- pq commented Dec 26, 2018
- alexander-doroshko commented Dec 26, 2018
- james-lawrence commented Dec 26, 2018
- alexander-doroshko commented Dec 26, 2018
- EHBradford commented Mar 28, 2019
- EHBradford commented Apr 8, 2019
- Android Studio lock unlock file make read only or writable
- Další témata . (Topics)
- Snow Text Effects Paint.NET | snow-text-effects-paint-net
- Eclipse Error parsing the sdk Android | eclipse-error-parsing-the-sdk-android
- Map TreeMap get values to array Java Android example | map-treemap-get-values-to-array-java-android-example
- Activity Lifecycle if button Home pressed Android example | activity-lifecycle-if-button-home-pressed-android-example
- Lenovo A6000 smartphone pictures from camera 8mpx review | lenovo-a6000-smartphone-pictures-from-camera-8mpx
- Работа с файловой системой
- Чтение и сохранение файлов
- Методы лечения различных ошибок в Android Studio при разработке проекта
android studio put itself into read only mode for all files #2994
Comments
james-lawrence commented Dec 23, 2018
Steps to Reproduce
standard development for flutter, somehow android studio decided every file was read only (which was not the case). seems clearing .idea directories fixed the issue. but this sort of behavior isn’t acceptable.
begging that flutter move away from android studio as the defacto development environment. its extremely fragile and brittle. to the point where everytime I’ve tried to use android studio I spend more time debugging the IDE than actually writing code.
Version info
The text was updated successfully, but these errors were encountered:
pq commented Dec 25, 2018 •
Sorry you had this experience. It would be great for us to track down what happened so please do share whatever context you can. Certainly if this recurs.
begging that flutter move away from android studio as the defacto development environment. its extremely fragile and brittle. to the point where everytime I’ve tried to use android studio I spend more time debugging the IDE than actually writing code.
Again, this is really unfortunate. If you have any actionable feedback we can pass on to the Android Studio team we’d be happy to.
Thanks again for the report and do check back if you hit any other issues.
PS: we’ve had a few quick releases of the flutter plugin since 31.3.1 to address a number of issues. Worth an update for sure.
EDIT: Sorry, misread. You’re up to date.
james-lawrence commented Dec 25, 2018
problem is I’m not even sure how to debug these issues. android studio is extremely opaque regarding errors.
pq commented Dec 26, 2018
android studio is extremely opaque regarding errors.
@alexander-doroshko : any suggestions that may help debug AS in general?
alexander-doroshko commented Dec 26, 2018
To narrow down the «read-only mode» problem I’d first ask what the problem looks like.
Was it a dialog saying ‘You are trying to edit non-project file. Are you sure?’? If so then it means that the project structure somehow got messed up and the files appeared to be outside of the configured content roots.
The root cause might be the same as in #2993. My guess is that it could be related to Gradle. I’m not an expert in Gradle, neither in its support in the IDE. Just a guess: on Gradle project reimport all the current IDE project configuration is wiped out and reconfigured from scratch based on gradle config file. So content roots might be changed as well as module dependencies, which means that knowledge that that was a Flutter project gets lost.
The cause might be different.
james-lawrence commented Dec 26, 2018
@alexander-doroshko the read only mode presented itself when editing the files themselves. AS would just ignore my input and display a little note saying read only. i ‘fixed’ the issue by deleting gradle and .idea caches. havent been able to reproduce it. #2993 still happens all the time though.
alexander-doroshko commented Dec 26, 2018
the read only mode presented itself when editing the files themselves. AS would just ignore my input and display a little note saying read only.
Not sure I understand. Should you see it again please paste a screenshot. Thanks!
Speaking of #2993, Gradle reimport is probably deleting knowledge about Flutter from the IDE project files. Gradle doesn’t know anything about Dart/Flutter, so maybe Flutter projects shouldn’t be backed by Gradle config. Sorry, not my area of expertise. Not sure I can help much with it. I think responsible developers might be interested in a sample project they could use to reproduce the issue.
EHBradford commented Mar 28, 2019
Since no one ever provided you with a screen shot here it is. Every file in Android Studio is locked, I cannot edit anything. BTW I know that the res definitions as shown in this example are wrong, I was working on fixing the issue when I suddenly am no longer able to edit any file.
The little popup message happens on any edit action, such as hitting enter or any other character.
EHBradford commented Apr 8, 2019
I continue to have this issue. Have tracked it down in Android Studio 3.3.2 to when I go to Open Module Settings (F4) and I create the APK module, press Apply, and then Ok all of my files are now locked with Android Studio.
To restore my ability to edit the project I have to Re-import Gradle Project. But as soon as I do that I loose all of my «Modules» that I created using the Open Module Settings (F4) window.
Источник
Android Studio lock unlock file make read only or writable
Select file in project explorer
Menu:
File — Make File Read-only — to lock
File — Make File Writable — to unlock
397LW NO topic_id
Další témata . (Topics)
Snow Text Effects Paint.NET | snow-text-effects-paint-net
For some graphics you can use Paint.NET editor.
//www.getpaint.net/
How create Snow Effects on Text by 1 minute show this video:
Eclipse Error parsing the sdk Android | eclipse-error-parsing-the-sdk-android
[2013-07-06 16:10:29 — SDK Manager] [SDK Manager] Error: Error parsing the sdk.
[2013-07-06 16:10:29 — SDK Manager] [SDK Manager] Error: Failed to create C:\Program Files\android\sdk\add-ons.
[2013-07-06 16:10:29 — SDK Manager] [SDK Manager] Error: Unable to parse SDK content.
You have to create add-ons folder as admin of PC
Map TreeMap get values to array Java Android example | map-treemap-get-values-to-array-java-android-example
Activity Lifecycle if button Home pressed Android example | activity-lifecycle-if-button-home-pressed-android-example
If on Android emulator home button pressed.
Diagram of Activity lifecycle if button HOME pressed
Lenovo A6000 smartphone pictures from camera 8mpx review | lenovo-a6000-smartphone-pictures-from-camera-8mpx
Pictures taken by front camera Lenovo A6000 smartpohone — review.
Do not take pictures against the sun.
Stay in the shade. Keep lens clean.
Night without flash
Misty — smog
Without flash in room — TV screen
Editace: 2015-12-04 19:50:55
Počet článků v kategorii: 397
Url:android-studio-lock-unlock-file-make-read-only-or-writable
Источник
Работа с файловой системой
Чтение и сохранение файлов
Работа с настройками уровня activity и приложения позволяет сохранить небольшие данные отдельных типов (string, int), но для работы с большими массивами данных, такими как графически файлы, файлы мультимедиа и т.д., нам придется обращаться к файловой системе.
ОС Android построена на основе Linux. Этот факт находит свое отражение в работе с файлами. Так, в путях к файлам в качестве разграничителя в Linux использует слеш «/», а не обратный слеш «\» (как в Windows). А все названия файлов и каталогов являются регистрозависимыми, то есть «data» это не то же самое, что и «Data».
Приложение Android сохраняет свои данные в каталоге /data/data/ / и, как правило, относительно этого каталога будет идти работа.
Для работы с файлами абстрактный класс android.content.Context определяет ряд методов:
boolean deleteFile (String name) : удаляет определенный файл
String[] fileList () : получает все файлы, которые содержатся в подкаталоге /files в каталоге приложения
File getCacheDir() : получает ссылку на подкаталог cache в каталоге приложения
File getDir(String dirName, int mode) : получает ссылку на подкаталог в каталоге приложения, если такого подкаталога нет, то он создается
File getExternalCacheDir() : получает ссылку на папку /cache внешней файловой системы устройства
File getExternalFilesDir(String type) : получает ссылку на каталог /files внешней файловой системы устройства
File getFileStreamPath(String filename) : возвращает абсолютный путь к файлу в файловой системе
FileInputStream openFileInput(String filename) : открывает файл для чтения
FileOutputStream openFileOutput (String name, int mode) : открывает файл для записи
Все файлы, которые создаются и редактируются в приложении, как правило, хранятся в подкаталоге /files в каталоге приложения.
Для непосредственного чтения и записи файлов применяются также стандартные классы Java из пакета java.io.
Итак, применим функционал чтения-записи файлов в приложении. Пусть у нас будет следующая примитивная разметка layout:
Поле EditText предназначено для ввода текста, а TextView — для вывода ранее сохраненного текста. Для сохранения и восстановления текста добавлены две кнопки.
Теперь в коде Activity пропишем обработчики кнопок с сохранением и чтением файла:
При нажатии на кнопку сохранения будет создаваться поток вывода FileOutputStream fos = openFileOutput(FILE_NAME, MODE_PRIVATE)
В данном случае введенный текст будет сохраняться в файл «content.txt». При этом будет использоваться режим MODE_PRIVATE
Система позволяет создавать файлы с двумя разными режимами:
MODE_PRIVATE : файлы могут быть доступны только владельцу приложения (режим по умолчанию)
MODE_APPEND : данные могут быть добавлены в конец файла
Поэтому в данном случае если файл «content.txt» уже существует, то он будет перезаписан. Если же нам надо было дописать файл, тогда надо было бы использовать режим MODE_APPEND:
Для чтения файла применяется поток ввода FileInputStream :
Подробнее про использование потоков ввода-вывода можно прочитать в руководстве по Java: https://metanit.com/java/tutorial/6.3.php
В итоге после нажатия кнопки сохранения весь текст будет сохранен в файле /data/data/название_пакета/files/content.txt
Где физически находится созданный файл? Чтобы увидеть его на подключенном устройстве перейдем в Android Stud в меню к пункту View -> Tool Windows -> Device File Explorer
После этого откроектся окно Device File Explorer для просмотра файловой системы устройства. И в папке data/data/[название_пакета_приложения]/files мы сможем найти сохраненный файл.
Источник
Методы лечения различных ошибок в Android Studio при разработке проекта
Сегодня хотел бы поделиться своим анализом и способами лечением разных ошибок при разработке своего продукта в Android Studio. Лично я, не раз сталкивался с различными проблемами и ошибками при компиляции и/или тестировании мобильного приложения. Данный процесс, всегда однообразный и в 99% случаев и всегда нужно тратить n-колличество времени на его устранение. Даже, когда ты уже сталкивался с данной проблемой, ты все равно идешь в поисковик и вспоминаешь, как же решить ту или иную ситуацию.
Я для себя завел файлик, в котором отметил самые частые ошибки — потратив на это несколько часов и перечислил самые популярные ошибки (в дальнейшем планирую просто их запомнить), чтоб сократить свое время в дальнейшем.
Итак, начну по порядку с самой распространенной проблемы и дальше буду перечислять их по мере появления:
1) Если подчеркивает красным код, где используются ресурсы: R. — попробовать (но вероятно не поможет): Build -> Clean Project.
В принципе на Build -> Clean Project можно не терять времени, а лучше всего — слева переключиться на Project, открыть каталог .idea, затем каталог libraries и из него удалить все содержимое. Затем нажать кнопку Sync Project. А затем (если все еще красное, но скорее всего уже будет все ок ) Build -> Clean Project.
2) После внезапного выключения компьютера, после перезапуска может быть во всех проектах весь код красным. Перед этим может быть ошибка: Unable to create Debug Bridge: Unable to start adb server: Unable to obtain result of ‘adb version’. Есть три решения — первое помогло, второе нет (но может быть для другого случая), а третье — не пробовал:
а) File — Invalidate Caches/Restart — Invalidate and Restart
б) Закрыть студию. В корне папки проекта удалить файл(ы) .iml и папку .idea. Вновь запустить студию и импортировать проект.
в) Нажать Ctrl-Alt-O и запустить оптимизацию импорта.
Кстати, adb сервер можно проверить на версию (и работоспособность) и затем перезапустить:
3) Если Android Studio выдает приблизительно такую ошибку: Error:Execution failed for task ‘:app:dexDebug’.
Надо слева переключиться на опцию Project, найти и удалить папку build которая лежит в папке app, т.е. по пути app/build. Затем перестроить весь проект заново: Build -> Rebuild Project.
Такое же решение если ошибка типа: «не могу удалить (создать) папку или файл» и указан путь, который в ведет в app/build. Тоже удаляем папку build и ребилдим проект.
4) В сообщении об ошибке упоминается heap — виртуальная память. А ошибка обычно вызвана ее нехваткой, т.е. невозможностью получить запрашиваемый объем. Поэтому этот запрашиваемый объем надо уменьшить, т.е. переписать дефолтное значение (обычно 2048 MB которое можно изменить в настройках), на меньшее 1024 MB.
В файле проекта gradle.properties пишем:
5) Android Studio пришет примерно такую ошибку: Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to «83648b99316049d63656d7276cb19cc7e95d70a5»
Возможные причины (кроме необходимости регулярного обновления SDK):
а) Загруженный проект был скомпилирован с помощью уже несовместимого старого gradle плагина. В этом случае надо найти и подключить в своем build.gradle проекта этот более старый плагин. т.е. попробовать более старые версии, например: 1.1.3 (часто именно 1.1.x и подходит).
Найти все версии можно здесь.
б) Если в build.gradle проекта используется beta-версия плагина — это означает, что срок ее истек. Посмотреть последние релизы (продакшн и бета) можно также здесь:
6) Иногда при подключении сторонних библиотек могут дублироваться некоторые файлы (обычно связанные с лицензированием). В сообщении будет что-то содержащее слова: duplicate files. Решение — надо посмотреть в сообщении об ошибке или в документации подключенной сторонней библиотеки — какие именно файлы стали избыточными, и перечислить их в build.gradle модуля для исключения (exclude) из билда.
Это делается в директиве packagingOptions (которая, в свою очередь, находится в директиве android).
Источник