FileStorage.cpp Example File
persistentobjects/src/FileStorage.cpp
#include "FileStorage.hpp"
#include "Person.hpp"
using namespace bb::cascades;
const QString FileStorage::m_personsFilePath = "./data/PersonList.dat";
FileStorage::FileStorage()
{
}
FileStorage::~FileStorage()
{
}
bool FileStorage::clear()
{
QFile peopleFile(m_personsFilePath);
return peopleFile.remove();
}
bool FileStorage::save(int lastID, GroupDataModel *model)
{
QFile personFile(m_personsFilePath);
if (!personFile.open(QIODevice::WriteOnly))
return false;
QDataStream stream(&personFile);
const bool saved = serializeDataModel(lastID, model, &stream);
personFile.close();
return saved;
}
bool FileStorage::serializeDataModel(int lastID, GroupDataModel* model, QDataStream* stream)
{
bool addedData = false;
*stream << lastID;
if (stream->status() == QDataStream::Ok) {
for (int i = 0; i < model->size(); i++) {
Person *person = (Person *) model->children()[i];
*stream << person->customerID() << person->firstName()
<< person->lastName();
if (stream->status() != QDataStream::Ok) {
return addedData = false;
}
}
addedData = true;
}
return addedData;
}
int FileStorage::load(int& lastID, GroupDataModel *model)
{
int loadedCount = 0;
QFile file(m_personsFilePath);
if (!file.open(QIODevice::ReadOnly)) {
return loadedCount;
}
QDataStream stream(&file);
loadedCount = deserializeIntoDataModel(&stream, model, lastID);
file.close();
return loadedCount;
}
int FileStorage::deserializeIntoDataModel(QDataStream *stream, GroupDataModel *model, int& lastID)
{
int loadedCount = 0;
if (stream->atEnd())
return loadedCount;
if (!loadLastCustomerID(stream, lastID))
return loadedCount;
while (!stream->atEnd()) {
if (loadPerson(stream, model)) {
loadedCount++;
} else {
break;
}
}
return loadedCount;
}
bool FileStorage::loadPerson(QDataStream* stream, GroupDataModel *model)
{
bool loaded = false;
QString id, firstName, lastName;
*stream >> id >> firstName >> lastName;
if (stream->status() == QDataStream::Ok) {
model->insert(new Person(id, firstName, lastName));
loaded = true;
}
return loaded;
}
bool FileStorage::loadLastCustomerID(QDataStream* stream, int& id)
{
bool loaded = false;
int lastID;
*stream >> lastID;
if (stream->status() == QDataStream::Ok) {
loaded = true;
id = lastID;
}
return loaded;
}