Skip to content
This repository has been archived by the owner. It is now read-only.
Open

Ver1 #16

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions EpicDatabseExample/.idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,15 @@ abstract class NoteDatabase : RoomDatabase() {
database.execSQL("ALTER TABLE $NOTE_TABLE " +
"ADD COLUMN ${NoteEntity.COLUMN_PERSON_NAME} TEXT NOT NULL " +
"DEFAULT ('${PersonEntity.DEFAULT_PERSON_NAME}')")
// /*в принципе можно и здесь - пусть это будет 2ая версия*/database.execSQL("ALTER TABLE $NOTE_TABLE ADD COLUMN ${NoteEntity.COLUMN_IS_COMPLETED} INTEGER NOT NULL DEFAULT(0)")
}
},
// TODO Добавить миграцию.
object : Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("ALTER TABLE $NOTE_TABLE ADD COLUMN ${NoteEntity.COLUMN_IS_COMPLETED} INTEGER NOT NULL DEFAULT(0)")
}
},
)

private fun createDatabaseInstance(application: Application): NoteDatabase {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,11 @@ abstract class NoteDao {
// Что можно указать в качестве возвращаемого типа?
// Напомню, что выше есть метод observeNoteList, который будет вызываться при любом
// изменении списка в Базе Данных.

@Query("update note_table set title = :noteTitle, DESCRIPTIONS = :noteDescription," +
"PERSON_NAME = :notePersonName, IS_COMPLETED = :noteIsCompleted where id =:noteId")
abstract fun updateNote(noteTitle: String, noteDescription: String , notePersonName: String , noteIsCompleted: Boolean, noteId: Int) : Completable

@Update(/*entity = NoteEntity::class,*/onConflict = OnConflictStrategy.REPLACE)
abstract fun updateNote2(obj: NoteEntity): Completable
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ data class NoteEntity(
@ColumnInfo(name = COLUMN_PERSON_NAME)
var personName: String = PersonEntity.DEFAULT_PERSON_NAME,

@ColumnInfo(name = COLUMN_IS_COMPLETED)
var isCompleted: Boolean = PersonEntity.DEFAULT_IS_COMPLETED,


// TODO Нужно добавить нове поле isCompleted типа Boolean.
// В SQLite не поддерживается Boolean, но в Room его можно использовать.
// Поэтому поле делаем именно Boolean, а при добавлении миграции - нужно будет погуглить,
Expand All @@ -33,5 +37,6 @@ data class NoteEntity(
const val COLUMN_TITLE = "title"
const val COLUMN_DESCRIPTION = "descriptions"
const val COLUMN_PERSON_NAME = "person_name"
const val COLUMN_IS_COMPLETED = "is_completed"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ data class PersonEntity(
companion object {
const val COLUMN_NAME = "name"
const val DEFAULT_PERSON_NAME = "UNKNOWN"
const val DEFAULT_IS_COMPLETED = false
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,20 @@ class NoteListAdapter(
// if (isCompletedChanged) {
// holder.isCompleted.isChecked = note.isCompleted
// }

//\\
holder.isCompleted.setOnClickListener {
onIsCompletedClick.invoke(note.copy(
isCompleted = !note.isCompleted
))
}
val isCompletedChanged = note.isCompleted != holder.isCompleted.isChecked
if (isCompletedChanged) {
holder.isCompleted.isChecked = note.isCompleted
}


//\\

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import com.example.epicdatabaseexample.ui.NavigationCommand
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers

const val ver = 1
class NoteListViewModel constructor(
private val noteDao: NoteDao,
) : ViewModel() {
Expand Down Expand Up @@ -65,6 +65,19 @@ class NoteListViewModel constructor(

fun onIsCompletedClick(note: NoteEntity) {
// TODO Добавить вызов noteDao для обновления элемента в таблице.
if (ver == 1)
{
compositeDisposable.add(noteDao.updateNote2(note)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe())
} else
{
compositeDisposable.add(noteDao.updateNote(note.title,note.description,note.personName,note.isCompleted,note.id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe())
}
}

override fun onCleared() {
Expand Down
30 changes: 29 additions & 1 deletion HomeWorkNetwork/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,27 @@ plugins {
android {
compileSdk 31

packagingOptions {
/* A failure occurred while executing com.android.build.gradle.internal.tasks.MergeJavaResWorkAction
*/
pickFirst 'META-INF/DEPENDENCIES'
pickFirst 'META-INF/INDEX.LIST'
pickFirst 'META-INF/io.netty.versions.properties'
}





defaultConfig {

buildConfigField "String", "API_BASE_URL", '"api.themoviedb.org"'
buildConfigField "String", "API_KEY", '"/*ваш ap_key*/"'
buildConfigField "String", "API_KEY", '"14b7da11c0f7fbc92f26a7cbcd9ff925"'
buildConfigField "String", "API_IMAGE_BASE_URL", '"https://image.tmdb.org/t/p/w500"'

applicationId "com.pg.homeworknetwork"
minSdk 30

targetSdk 31
versionCode 1
versionName "1.0"
Expand All @@ -28,6 +41,9 @@ android {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}



compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
Expand All @@ -38,6 +54,7 @@ android {
}

dependencies {
def v_ktr = '1.6.8'
//Coil (загрузка постеров)
implementation "io.coil-kt:coil-compose:2.0.0-rc02"

Expand All @@ -46,4 +63,15 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
//my
implementation("io.ktor:ktor-server-core:${v_ktr}")
implementation("io.ktor:ktor-server-netty:${v_ktr}")
implementation("ch.qos.logback:logback-classic:1.2.5")
implementation("io.ktor:ktor-client-logging:${v_ktr}")
implementation("io.ktor:ktor-client-serialization:${v_ktr}")
implementation("io.ktor:ktor-client-cio:${v_ktr}")
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2"


//
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,40 @@
package com.pg.homeworknetwork

import kotlinx.serialization.*

@Serializable
class Movies
(
@SerialName("page")
val page: Int,
@SerialName("result")
val result : List<Movie> =ArrayList(),
@SerialName("total_results")
val total_results: Int,
@SerialName("total_pages")
val total_pages: Int
)


class Movie
@Serializable
data class Movie
(
@SerialName("id") //TODO рассказать
val id: Int,
@SerialName("title")
val title: String? = null,
@SerialName("poster")
val poster: String? = null,
//
@SerialName("poster_patch")
val posterPath: String? = null,
//
@SerialName("original_title")
val originalTitle: String? = null,
@SerialName("overview")
val overview: String? = null,
@SerialName("popularity")
val popularity: Double? = null,
@SerialName("release_date")
val releaseDate: String? = null
)
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import coil.load
import coil.transform.RoundedCornersTransformation

//
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
//
class MovieDetailFragment : Fragment(R.layout.fragment_movie_preview) {

lateinit var poster: ImageView
lateinit var originalTitle: TextView
lateinit var overview: TextView
Expand All @@ -21,22 +25,39 @@ class MovieDetailFragment : Fragment(R.layout.fragment_movie_preview) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(view) {
println("view:"+ view)
poster = findViewById(R.id.poster)
originalTitle = findViewById(R.id.originalTitle)
overview = findViewById(R.id.overview)
popularity = findViewById(R.id.popularity)
releaseDate = findViewById(R.id.releaseDate)
}

val movieId = arguments?.getInt(ARG_ID) ?: 550
val movie = //получаем фильм
// val movieId = arguments?.getInt(ARG_ID) ?: 550
/*val movie = //получаем фильм
poster.load("${BuildConfig.API_IMAGE_BASE_URL}${movie.posterPath}") {
transformations(RoundedCornersTransformation(16f))
}
originalTitle.text = movie.originalTitle
overview.text = movie.overview
popularity.text = movie.popularity.toString()
releaseDate.text = movie.releaseDate
*/
CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
println("Корутина выполняется на потоке: ${Thread.currentThread().name}")
val movieId = arguments?.getInt(ARG_ID) ?: 550
println("movieId:"+ movieId)
val movie: Movie = Api().getMovie(movieId)
//получаем фильм
println("Movie:"+ Movie)
poster.load("${BuildConfig.API_IMAGE_BASE_URL}${movie.posterPath}") {
transformations(RoundedCornersTransformation(16f))
}
originalTitle.text = movie.originalTitle
overview.text = movie.overview
popularity.text = movie.popularity.toString()
releaseDate.text = movie.releaseDate
}

activity?.onBackPressedDispatcher?.addCallback(this.viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Expand All @@ -46,6 +67,11 @@ class MovieDetailFragment : Fragment(R.layout.fragment_movie_preview) {
transaction.commit()
}
})





}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@ import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
//
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

class MovieListFragment : Fragment(R.layout.fragment_movie_list) {
lateinit var recycler: RecyclerView

private val goToDetails = object : MovieItemAdapter.IOnItemClick {
private val goToDetails = object : MovieItemAdapter.IOnItemClick {
override fun onItemClick(movie: Movie) {
val manager: FragmentManager = parentFragmentManager
val transaction: FragmentTransaction = manager.beginTransaction()
Expand All @@ -31,8 +34,16 @@ class MovieListFragment : Fragment(R.layout.fragment_movie_list) {
}
}
val adapter = (recycler.adapter as MovieItemAdapter)
val movies = //получаем фильмы
/* val movies = //получаем фильмы
adapter.submitList(movies)

*/
CoroutineScope(SupervisorJob() + Dispatchers.Main).launch (Dispatchers.IO) {
val movies: Movies = Api().getMovies()
println("movies:"+ movies)
adapter.submitList(movies.result)
println("adapter:"+ adapter)
}
super.onViewCreated(view, savedInstanceState)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,63 @@
package com.pg.homeworknetwork
import io.ktor.client.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.logging.*
import io.ktor.client.request.*
/*import kotlinx.coroutines.runBlocking*/
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.json.Json

//@OptIn(ExperimentalSerializationApi::class)
class Api {
private val _base = "api.themoviedb.org"
private val _movies = "3/movie/popular"
private val _movie = "3/movie/"


//TODO добавить в предыдущий пример
val kLogger = object : Logger {
override fun log(message: String) {
if (message.contains("api_key=")) {
println("${message.split("=").first()}=BuildConfig.API_KEY")
} else {
println(message)
}
}
}

private val ktorClient = HttpClient() {
install(JsonFeature) {
serializer = KotlinxSerializer(kotlinx.serialization.json.Json {
prettyPrint = true
isLenient = true
ignoreUnknownKeys = true
})
}
install(Logging) {
logger = kLogger
level = LogLevel.BODY
}
}

suspend fun getMovie(movieId: Int): Movie = ktorClient.use {
it.get(
host = _base,
path = _movie + movieId.toString()
) {
parameter("api_key", BuildConfig.API_KEY)
}
}

suspend fun getMovies(): Movies = ktorClient.use {
it.get(
host = _base,
path = _movies
) {
parameter("api_key", BuildConfig.API_KEY)
}
}



}