Answer the question
In order to leave comments, you need to log in
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
Во-первых, судя по вашему описанию предметной области задачи (всего один тип объектов, фиксированный набор атрибутов объекта), база данных – то, что вам нужно. Не надо бояться инициализации объектов, потому что способа избежать восстановления объекта из хранилища (какое бы оно ни было) в данном случае нет: храните в базе – придётся инициализировать объект значениями столбцов таблицы; храните, скажем, в JSON – придётся инициализировать объект значениями, полученными из JSON-объекта (что, кстати, ещё менее удобно); используете Java-сериализацию – и там тоже будут накладные расходы на восстановление объекта из формата, в котором вы его сохранили, ну и так далее. А БД – очень удобный формат. К тому же, никто вас не заставляет инициализировать все-все объекты на старте программы: если у пользователя очень много заметок, то можно просто подгружать новые по мере листания списка.
Secondly, about
reminders are objects that it would be convenient to work with by directly accessing them by calling methods
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 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?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question