Нативная разработка мобильных приложений



Download 3,69 Mb.
Pdf ko'rish
bet205/228
Sana21.07.2022
Hajmi3,69 Mb.
#834838
1   ...   201   202   203   204   205   206   207   208   ...   228
Bog'liq
Нативная разработка мобильных приложений

catalog.json
в методе 
onCreate
и его запись в базу данных!
Java
public class DbHelper extends SQLiteOpenHelper {
private Context mContext;


Запись книг в хранилище 

329
public DbHelper(Context context, String name, 
SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(BOOKS_CREATE_TABLE);
database.execSQL(AUTHORS_CREATE_TABLE);
database.execSQL(BRIDGE_CREATE_TABLE);
InputStream stream = null;
try {
stream = mContext.getAssets().open("catalog.json");
String json = Files.getStringFromStream(stream);
Books books = new Gson().fromJson(json, Books.class);
for (Book book : books) {
BookTransactions.write(database, book);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.d("MyApp", BookTransactions.read(database, "978-0439136365").getTitle());
}
@Override
public void onUpgrade(SQLiteDatabase database, int i, int i1) {
// ничего не делает
}
public static final String BOOKS_TABLE_NAME = "BOOKS";
public static final String BOOKS_COLUMN_TITLE = "TITLE";
public static final String BOOKS_COLUMN_ISBN = "ISBN";
public static final String BOOKS_COLUMN_PAGECOUNT = "PAGECOUNT";
public static final String BOOKS_COLUMN_ISFICTION = "ISFICTION";
public static final String AUTHORS_TABLE_NAME = "AUTHORS";
public static final String AUTHORS_COLUMN_ID = "ID";
public static final String AUTHORS_COLUMN_NAME = "NAME";
public static final String BRIDGE_TABLE_NAME = "BOOK_AUTHOR_BRIDGE";
public static final String BRIDGE_COLUMN_BOOK_ID = "BOOK_ID";
public static final String BRIDGE_COLUMN_AUTHOR_ID = "AUTHOR_ID";
public static final String BOOKS_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " +
BOOKS_TABLE_NAME + " (" +


330

Сохранность данных
BOOKS_COLUMN_TITLE + " TEXT," +
BOOKS_COLUMN_ISBN + " TEXT," +
BOOKS_COLUMN_PAGECOUNT + " INT," +
BOOKS_COLUMN_ISFICTION + " BOOL);";
public static final String AUTHORS_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " +
AUTHORS_TABLE_NAME + " (" +
AUTHORS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
AUTHORS_COLUMN_NAME + " TEXT)";
public static final String BRIDGE_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " +
BRIDGE_TABLE_NAME +
" (" +
BRIDGE_COLUMN_BOOK_ID + " INTEGER REFERENCES BOOKS," +
BRIDGE_COLUMN_AUTHOR_ID + " INTEGER REFERENCES AUTHORS)";
}
Kotlin
class DbHelper(private val context: Context, name: String,
factory: SQLiteDatabase.CursorFactory,
version: Int) : 
SQLiteOpenHelper(mContext, name, factory, version) {
override fun onCreate(database: SQLiteDatabase) {
database.execSQL(BOOKS_CREATE_TABLE)
database.execSQL(AUTHORS_CREATE_TABLE)
database.execSQL(BRIDGE_CREATE_TABLE)
val stream = context.assets.open("catalog.json")
stream.use { s ­>
val json = Files.getStringFromStream(s)
val books = Gson().fromJson(json, Books::class.java)
for (book in books) {
BookTransactions.write(database, book)
}
}
}
override fun onUpgrade(database: SQLiteDatabase, i: Int, i1: Int) {
// ничего не делает
}
companion object {
const val BOOKS_TABLE_NAME = "BOOKS"
const val BOOKS_COLUMN_TITLE = "TITLE"
const val BOOKS_COLUMN_ISBN = "ISBN"
const val BOOKS_COLUMN_PAGECOUNT = "PAGECOUNT"
const val BOOKS_COLUMN_ISFICTION = "ISFICTION"
const val AUTHORS_TABLE_NAME = "AUTHORS"
const val AUTHORS_COLUMN_ID = "ID"
const val AUTHORS_COLUMN_NAME = "NAME"
const val BRIDGE_TABLE_NAME = "BOOK_AUTHOR_BRIDGE"
const val BRIDGE_COLUMN_BOOK_ID = "BOOK_ID"


Запись книг в хранилище 

331
const val BRIDGE_COLUMN_AUTHOR_ID = "AUTHOR_ID"
const val BOOKS_CREATE_TABLE = 
"CREATE TABLE IF NOT EXISTS " + BOOKS_TABLE_NAME +
" (" +
BOOKS_COLUMN_TITLE + " TEXT," +
BOOKS_COLUMN_ISBN + " TEXT," +
BOOKS_COLUMN_PAGECOUNT + " INT," +
BOOKS_COLUMN_ISFICTION + " BOOL);"
const val AUTHORS_CREATE_TABLE = 
"CREATE TABLE IF NOT EXISTS " + AUTHORS_TABLE_NAME +
" (" + 
AUTHORS_COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
AUTHORS_COLUMN_NAME + " TEXT)"
const val BRIDGE_CREATE_TABLE = 
"CREATE TABLE IF NOT EXISTS " + BRIDGE_TABLE_NAME +
" (" +
BRIDGE_COLUMN_BOOK_ID + " INTEGER REFERENCES BOOKS," +
BRIDGE_COLUMN_AUTHOR_ID + " INTEGER REFERENCES AUTHORS)"
}
}
Теперь при первой попытке получить экземпляр 
SqliteDatabase
в классе 
Db­
Helper
запустится метод 
onCreate
и заполнит базу данных содержимым файла 
catalog.json
, который устанавливается вместе с приложением, в специальном 
каталоге 
assets
! Неплохо!
Мы потратили много времени на создание слоя хранения данных. Зато те
-
перь готовы показать на экране сохраненные книги, но прежде чем двинуться 
дальше, реализуем все то же самое в iOS.
iOS
В Android мы использовали базу данных, к которой можно выполнять запросы 
SQL для получения данных. В iOS есть возможность работать с хранилищем не
-
посредственно из кода на Swift, без посредничества SQL: механизм Core Data.

Download 3,69 Mb.

Do'stlaringiz bilan baham:
1   ...   201   202   203   204   205   206   207   208   ...   228




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish