Properties file android app

Properties file android app

Android @Properties

This lib provides a simple way to read a .properties from assets folder.

You just have to extends from AssetsProperties and use @Property annotation to invoke the automatic property mapping.

It’s very simple with gradle 😉

Add mavenCentral as repository source:

And finnaly add this line inside dependencies < >section:

The + symbol indicates to gradle to get the latest version.

  • See the sample if there are any doubts.

Super simple usage 😉

Android Properties can parse String , int , float , double and boolean values from file .properties .

Create a class that represents your file properties and extend from AssetsProperties class.

assets/config.properties

Config.java

You must use @Property annotation to map field as property field from file. Pass the name of property if it’s different from the field name in class.

Read another file properties

The default file for properties is called config.properties but if you need to read another file properties, just pass the name of file in the constructor:

Map property name

The @Property annotation uses the name of field as name of property field in file. So if the field name is diferent of the name in file, just pass the name of property by @Property(«property_name») .

Useful public methods

If you do not want to use @Property annotation or need only a reader property class you can use some public methods from AssetsProperties :

If the AssetsProperties can’t read the key then the defaultValue will be returned.

There are a simple test for the rating dialog. If you want to contribute check the tests too.

You must open an emulator before.

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

Android Library for reading properties file stored in assets folder

Источник

Using local.properties file to avoid API Keys check-in into Version Control System

One of the best benefits of being an Android Developer is that we can create and contribute to open source projects! We can share our code with millions of developers around the globe. Thanks to code hosting platforms like GitHub!

Now, when we make our code available as public repositories, we should ensure we take care of some things such as the sharing of private API keys, restricted URLs, etc., How can we achieve this by using the “local.properties” file in our root project? Let’s find out in this article.

Читайте также:  Свой андроид определить уровень

Welcome to our MindOrks blog on Using local.properties file to avoid API Keys check-in into Version Control System.

Every time, we create a new project in Android Studio, we see a file created with the name “local.properties” containing the following content:

So local.properties is a file that is generated by Android Studio and it is recommended not to include this in the version control system.

So, if we take a look at our gitignore files in general, we have:

We can see that local.properties file is excluded in the version control system.

Tip: Updating the gitignore files with the relevant extensions and file folders is really important for creating an open-source project. Since the “local.properties” file is not shared in the version control system, we can use this for declaring our local user-specific variables or private variables such as API keys or restricted base URLs, etc.,

Let’s take a use case. Let’s consider our recently released open-source project on GitHub:

This project helps to build a ride-sharing Android Taxi Clone App like Uber, Lyft. You can fork it and learn many awesome functionalities. Please go through the Readme file for details of the project.

Now, since our use case is a ride-sharing application, we will be using google maps in it. To use Google Maps, the developer should have an associated API Key. Let’s see how we can achieve this by using “local.properties” file.

First of all, let’s append a parameter in the local.properties file:

Now, let’s extract this value and use it in our app-level Gradle file through a variable.

In order to access our API key, we can use:

There are some files that get generated during build time such as gradleResValues.xml, BuildConfig.java, etc. Let’s make the use of these files to store the value of our API key. How can we add values to files that are generated during the build process? We shall use our buildTypes section in our app-level build.gradle file

Now once we add this in our build.gradle file, we rebuild our project and we can see a file named gradleResValues.xml is generated in the res(generated) folder.

In order to use this value inside the application, we can try extracting the values like follows:

If we wish to store the value in the BuildConfig.java file, we can replace the resValue with buildConfigField in the app-level build.gradle file as follows:

After changing the build.gradle file, let’s rebuild the project and take a look at our BuildConfig.java file:

Now, we can access this parameter anywhere in the code like

Источник

Add version.properties file to your Android Project

Change version name and version code from one file and reflect the changes on all the product flavors

Jan 18, 2019 · 2 min read

T his story is from what I have learned today, As we all have the build variants in our project and In every product flavors we have version name and version code, whenever we published the build to the play store we increase our version code and version name and change in our all product flavor one by one….

Читайте также:  Android studio mqtt пример

What If we add a file called version.properties in our project and change the version name and version code from this file and then it will reflect it on our all the product flavors, let’s start how we gonna achieve this.

Step1:

A d d a file called version.properties in your project -> app folder.

Step2:

Add version code and version name in this file.

Step3:

Now, this is the main part everything is set up now, and we need to read the file in our build.gradle.

That’s it now define the code and name in your every product flavor like below:

If you want to learn more related to Android then check it out the below link:

Источник

Примеры работы с Java Properties

Большинству программ Java в какой-то момент необходимо использовать свойства, как правило, для хранения простых параметров в виде пар ключ-значение вне скомпилированного кода.

Таким образом, язык имеет поддержку класса для свойств – java.util.Properties – служебный класс, предназначенный для обработки файлов конфигурации этого типа.

В этой статье я покажу использование базового класса Properties, в том числе способы загрузки и сохранения в формате XML, как управлять парами ключ-значение в объекте свойств, например извлекать значения, обновлять, получить его размер и как использовать список по умолчанию для объекта.

  • Properties является подклассом Hashtable. Он используется для ведения списков значений, в которых ключ является строкой, а значение также является строкой.
  • Класс Properties используется многими другими классами Java. Например, это тип объекта, возвращаемый System.getProperties() при получении значений.
  • Одна полезная возможность класса состоит в том, что вы можете указать свойство по умолчанию, которое будет возвращаться, если никакое значение не связано с определенным ключом.
  • Несколько потоков могут совместно использовать один объект без необходимости внешней синхронизации.
  • Properties определяет переменную экземпляра.
  • Properties() создает объект Properties, который не имеет значений по умолчанию.
  • Properties (Properties propDefault): второй создает объект, который использует propDefault в качестве значения по умолчанию.
Метод и описание
1 String getProperty (String key) Возвращает значение, связанное с ключом. Пустой объект возвращается, если ключ отсутствует в списке или в списке свойств по умолчанию.
2 String getProperty (String key, String defaultProperty) возвращает значение, связанное с ключом; defaultProperty возвращается, если ключ не находится ни в списке, ни в списке свойств по умолчанию.
3 void list (PrintStream streamOut) Отправляет список свойств в выходной поток, связанный с streamOut.
4 void list (PrintWriter streamOut) Отправляет список свойств в выходной поток, связанный с streamOut.
5 void load (InputStream streamIn) throws IOException Вводит список свойств из входного потока, связанного с streamIn.
6 Перечисление propertyNames() Возвращает перечисление ключей. Сюда входят также ключи, найденные в списке свойств по умолчанию.
7 Объект setProperty (String key, String value) Связывает значение с ключом. Возвращает предыдущее значение, связанное с ключом, или возвращает null, если такой ассоциации не существует.
8 void store (OutputStream streamOut, String description) После записи строки, указанной в описании, список свойств записывается в выходной поток, связанный с streamOut.

Начнем с примера загрузки пар ключ-значение из файлов свойств; мы загружаем два файла, которые мы имеем в нашем classpath:

Обратите внимание, что в файлах свойств рекомендуется использовать “.properties”, в suffix это не обязательно.

Теперь мы можем очень просто загрузить их в экземпляр Properties:

Если содержимое файла соответствует требованиям формата файла свойств, оно может быть правильно проанализировано классом Properties.

Загрузка из файлов XML

Помимо файлов, класс Properties также может загружать файлы XML, которые соответствуют определенным спецификациям DTD.

Вот пример для загрузки пар ключ-значение из файла XML – icons.xml:

Теперь давайте загрузим:

Как получить свойства?

Мы можем использовать getProperty (ключ String) и getProperty (ключ String, String defaultValue), чтобы получить значение по его ключу.

Если пара ключ-значение существует, оба метода будут возвращать соответствующее значение. Но если такой пары ключ-значение не существует, первая вернет null, а вторая вместо нее вернет defaultValue.

Обратите внимание, что хотя класс Properties наследует метод get() от класса Hashtable, я не рекомендую использовать его для получения значения. Поскольку его метод get() будет возвращать значение Object, которое может быть приведено только к String, а метод getProperty() уже обрабатывает значение Object правильно.

Код ниже выдаст исключение:
float appVerFloat = (float) appProps.get(«version»);

Как установить свойства

Мы можем использовать метод setProperty(), чтобы обновить существующую пару ключ-значение или добавить новую.

Класс Properties наследует метод put() и метод putAll() от класса Hashtable, я не рекомендую использовать их по той же причине, что и для метода get(): в свойствах могут использоваться только строковые значения.

Приведенный ниже код не будет работать так, как вы хотите, когда вы используете getProperty() для получения его значения, он вернет null:
appProps.put(«version», 2);

Удалить свойства

Если вы хотите удалить пару ключ-значение, вы можете использовать метод remove().

Хранение Properties

Класс Properties предоставляет метод store() для вывода пар ключ-значение.

Второй параметр используется для комментариев. Если вы не хотите писать какой-либо комментарий, просто используйте для него значение null.

Хранение в XML-файлах

Класс Properties также предоставляет метод storeToXML() для вывода пар ключ-значение в формате XML.

Второй параметр такой же, как и в методе store().

Объект Properties может содержать другой объект Properties в качестве списка свойств по умолчанию. Список свойств по умолчанию будет найден, если ключ свойства не найден в исходном.

Помимо “app.properties”, у нас есть еще один файл – “default.properties” – в classpath:

По умолчанию файлы свойств должны быть в кодировке ISO-8859-1 (Latin-1), поэтому обычно не следует использовать свойства с символами не из ISO-8859-1.

Мы можем обойти это ограничение с помощью таких инструментов, как JDK native2ascii или явное кодирование файлов, если это необходимо. Для файлов XML метод loadFromXML() и метод storeToXML() по умолчанию используют кодировку UTF-8.

Однако при чтении XML-файла, закодированного по-другому, мы можем указать это в объявлении DOCTYPE; запись также достаточно гибкая – мы можем указать кодировку в третьем параметре API storeToXML().

Полный исходный код проекта доступен на GitHub

Средняя оценка / 5. Количество голосов:

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Источник

Читайте также:  Штатное головное устройство android для nissan
Оцените статью