R
R
Riodevista2015-01-30 03:40:29
Java
Riodevista, 2015-01-30 03:40:29

How to properly organize the storage of objects in an Android application?

Hello!
I am writing a small application for Android - a simple organizer
. There are notes, which in turn have attributes, such as the time and date of a reminder, some text, an audio recording, maybe.
I can not decide how best to organize their storage.
You can make a table in the database for them, where there will be corresponding fields "time", "date", "text", "file path" (Then keep track that it remains the same).
But it seems to me that this approach is not entirely correct, because reminders are objects that it would be convenient to work with by directly accessing them by calling methods, for example, note1.delete() .
I have no idea how to solve this problem using objects. Suppose we have created several of them in the application, but what to do next? You have to store them somewhere. In the same database? Then at startup you will need to re-initialize them. Or is this process not so scary? But in this case, it is enough to write methods that work with the table in the same way as they would work with objects, but with the only difference that they are given as an argument the id of the row in the table, which will be a "pseudo-object", for example, deleteNote(1 ) .
How to do better? Maybe there are other approaches?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander P, 2015-01-30
@Riodevista

Во-первых, судя по вашему описанию предметной области задачи (всего один тип объектов, фиксированный набор атрибутов объекта), база данных – то, что вам нужно. Не надо бояться инициализации объектов, потому что способа избежать восстановления объекта из хранилища (какое бы оно ни было) в данном случае нет: храните в базе – придётся инициализировать объект значениями столбцов таблицы; храните, скажем, в JSON – придётся инициализировать объект значениями, полученными из JSON-объекта (что, кстати, ещё менее удобно); используете Java-сериализацию – и там тоже будут накладные расходы на восстановление объекта из формата, в котором вы его сохранили, ну и так далее. А БД – очень удобный формат. К тому же, никто вас не заставляет инициализировать все-все объекты на старте программы: если у пользователя очень много заметок, то можно просто подгружать новые по мере листания списка.
Secondly, about

reminders are objects that it would be convenient to work with by directly accessing them by calling methods

There is such a thing as the single responsibility principle (and the same in Russian ), the essence of which, in short, is that a class should only perform a specific limited range of responsibilities, and nothing more. In this case, your mistake is that you are thinking about giving the notes class responsibilities that it is not supposed to have. The annotation in this case is just an entity representing the stored data, nothing else, and it doesn't need to know anything about the storage layer, etc. So it definitely shouldn't have methods like delete(), save() and the like. And for the convenience of storing and loading objects, I suggest making a separate class like this (written on the knee just to convey the idea):
public class NotesManager {
       private final SQLiteDatabase db;

       public NotesManager(SQLiteDatabase db) { this.db = db; }

       public Note findById(int noteId) {
              Cursor c = db.query(...);
              //тут чтение в локальные переменные значений
              //отдельных полей из курсора,
              //если он вернул какой-то результат
              return new Note(...ранее считанные значения полей как аргументы конструктора...);
       }

       public void save(...перечисление полей...) {
              //после проверки введённых данных делаете 
              //insert в базу с переданными значениями полей 
       }
}

You will also need the create and delete methods, but if you understand the idea, then you can probably do it :) Ask more questions if something is not clear.

D
Denis I., 2015-02-01
@dplsoft

You can make a table in the database for them, where there will be corresponding fields "time", "date", "text", "file path" (Then keep track that it remains the same).
But it seems to me that this approach is not entirely correct, because reminders are objects that it would be convenient to work with by directly accessing them by calling methods, for example, note1.delete().
I have no idea how to solve this problem using objects. Suppose we have created several of them in the application, but what to do next? You have to store them somewhere. In the same database?

If it is convenient for you (yes, in principle, and correctly, although slower) to work with objects and not with records in the database, then there is such a thing as ORM for such things . ( Of course, you have a simple case, and therefore working with records in your project is just right. And even more so - if you are a beginner - you should figure out how to work with the database directly. But in general, as soon as you make a training project with a database - , it is worth understanding that in other complex projects - there will be much more problems with the database and it will be more difficult and better to get used to "industrial approaches" )
In general, there is an ORM. If deciphered, it is a "model / rules" that / which allow you to save the states of objects in the database and restore them.
But in practice, this is a set of classes that do all the dirty work for you to interact with the database (or the storage that lies underneath). And you are not working with a database, but with some kind of abstraction that hides from you what, where and how it stores in the database or the storage that the ORM uses.
Those. you say something like - " Oh, my ORM! give me an object of type 'MyNote' with ID 12345! " filled with note data with the number 12345. And then - "what you want with it, then do it."
And how did you do everything you need (by changing its methods, changing properties or whatever), - you give it back to your ORM layer (ORM can be considered as an abstraction layer over a database or any other storage) - like " here's an object for you, save it in the database. " - and ORM engines do all the hard work of generating SQL queries and everything else for you.
Depending on what the creators wanted from the orm, the ORM may or may not manage the database structure or try to pull its objects from a previously created structure; manage the metadata of your objects and (for example) whether or not to contain data on how these properties should be displayed or not.
Some ORMs have a code generator - i.e. you give him class descriptions, and he generates code for you that saves classes in the database and restores them from there. Part of the ORM mechanisms work based on annotations - i.e. you overwrite each of the fields that you want to save in the database with its name, type, indexing and other parameters - for example, the Persistence API does this - but it is not on Android, because this is not our case (and work through reflection is considered slow).
I can also give 2 links - to a comparative article of ORM for Android and to my own ORM bike:
www.ninthavenue.com.au/android-orm-jpa
https://gitorious.org/unat/pages/SimpleORM_Overvie...
(the last - "as advertising". my creation, but not updated in public for a long time. Now there are a lot of changes, as we hand over the current project - I will publish what is newer. In principle, not so much for use as for you - for mastering ideas and issuing constructive criticism and questions. if anything - ask - on UnAT I will tell you everything)) )

N
Nikolai Pavlov, 2015-01-30
@gurinderu

Not a bad option to look towards CouchbaseLite

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question