patient
Clogon 2023-08-23 08:59:38 +03:00
parent 2293d1f5cf
commit 6ea44be0cb
194 changed files with 19481 additions and 1757 deletions

View File

@ -7,11 +7,11 @@
<deviceKey> <deviceKey>
<Key> <Key>
<type value="VIRTUAL_DEVICE_PATH" /> <type value="VIRTUAL_DEVICE_PATH" />
<value value="C:\Users\oxsan\.android\avd\Pixel_6_API_33.avd" /> <value value="C:\Users\maksi\.android\avd\Pixel_5_API_29.avd" />
</Key> </Key>
</deviceKey> </deviceKey>
</Target> </Target>
</targetSelectedWithDropDown> </targetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2023-06-29T21:09:23.650986100Z" /> <timeTargetWasSelectedWithDropDown value="2023-08-22T15:06:26.067415300Z" />
</component> </component>
</project> </project>

View File

@ -6,4 +6,11 @@
<component name="ProjectType"> <component name="ProjectType">
<option name="id" value="Android" /> <option name="id" value="Android" />
</component> </component>
<component name="VisualizationToolProject">
<option name="state">
<ProjectState>
<option name="scale" value="0.33" />
</ProjectState>
</option>
</component>
</project> </project>

View File

@ -1,8 +1,8 @@
plugins { plugins {
id 'kotlin-kapt'
id 'com.android.application' id 'com.android.application'
id 'org.jetbrains.kotlin.android' id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt' id 'com.google.gms.google-services'
} }
android { android {
@ -42,10 +42,17 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.1' implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.6.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1' implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1'
implementation platform('com.google.firebase:firebase-bom:31.2.0')
implementation 'com.google.firebase:firebase-database-ktx:20.2.2'
implementation 'com.google.firebase:firebase-auth-ktx:22.1.0'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-messaging-ktx:23.2.0'
kapt 'androidx.room:room-compiler:2.5.2' kapt 'androidx.room:room-compiler:2.5.2'
implementation 'androidx.fragment:fragment-ktx:1.5.5' implementation 'androidx.fragment:fragment-ktx:1.5.5'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.1.17'
implementation 'androidx.core:core-ktx:1.7.0' implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0' implementation 'com.google.android.material:material:1.9.0'
@ -54,4 +61,23 @@ dependencies {
testImplementation 'junit:junit:4.13.2' testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
implementation 'org.apache.poi:poi:5.2.3'
implementation group: 'org.apache.poi', name: 'poi-ooxml', version: '5.2.3'
implementation group: 'org.apache.poi', name: 'poi', version: '5.2.3'
//Календарь
// implementation 'com.github.appmonkey8010:amcalendar:[RELEASE]' //e.g.: 1.0.0
//implementation 'ru.cleverpumpkin:crunchycalendar:2.6.0'
//implementation 'com.applandeo:material-calendar-view:1.9.0-rc03'
//implementation 'com.github.tejpratap46:RecyclerCalendarAndroid:LATEST_RELEASE_TAG'
//implementation 'com.github.tejpratap46:RecyclerCalendarAndroid:LATEST_RELEASE_TAG'
//implementation 'com.sun.mail:android-mail:1.6.2'
//implementation 'com.sun.mail:android-activation:1.6.2'
//implementation 'com.archit.calendar:awesome-calendar:2.0.0'
//implementation 'com.andrewjapar.rangedatepicker:rangedatepicker:0.3'
} }

View File

@ -0,0 +1,69 @@
{
"project_info": {
"project_number": "1027818028999",
"firebase_url": "https://rehabilitationtest-default-rtdb.europe-west1.firebasedatabase.app",
"project_id": "rehabilitationtest",
"storage_bucket": "rehabilitationtest.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:1027818028999:android:a97724d7840d06fdada3e2",
"android_client_info": {
"package_name": "com.example.rehabilitation"
}
},
"oauth_client": [
{
"client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAHvjzE2QIaIrCD9NOD1f_rShI4eXPyFVo"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:1027818028999:android:1459bab345b4bf66ada3e2",
"android_client_info": {
"package_name": "com.example.user"
}
},
"oauth_client": [
{
"client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAHvjzE2QIaIrCD9NOD1f_rShI4eXPyFVo"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "1027818028999-a75qvvvqqb81ber25k6eeq1fqpr60oam.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}

View File

@ -2,32 +2,79 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
<application <application
android:allowBackup="true" android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules" android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules" android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher_logov2"
android:label="@string/app_name" android:label="@string/app_name"
android:requestLegacyExternalStorage="true" android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_logo_rehabilitation" android:roundIcon="@mipmap/ic_launcher_logov2"
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.Rehabilitation" android:theme="@style/Theme.Rehabilitation"
android:usesCleartextTraffic="true"
tools:targetApi="31"> tools:targetApi="31">
<activity <activity
android:name=".Admin.activityAdmin.FeedbackActivity" android:name=".InformationActivity"
android:exported="false" /> android:exported="false" />
<activity
android:name=".Auth.AuthDoctorActivity"
android:exported="false" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
<activity
android:name=".Admin.activityAdmin.FeedbackActivity"
android:exported="false"
android:screenOrientation="portrait" />
<activity <activity
android:name=".Admin.activityAdmin.StatisticsActivity" android:name=".Admin.activityAdmin.StatisticsActivity"
android:exported="false" /> android:exported="false"
android:screenOrientation="portrait" />
<activity <activity
android:name=".Admin.activityAdmin.UserSettingActivity" android:name=".Admin.activityAdmin.UserSettingActivity"
android:exported="false" /> android:exported="false"
android:screenOrientation="portrait" />
<activity <activity
android:name=".SettingActivity" android:name=".SettingActivity"
android:exported="false" /> android:exported="false"
android:screenOrientation="portrait" />
<activity
android:name=".Auth.AuthorizationActivity"
android:exported="false">
<meta-data
android:name="android.app.lib_name"
android:screenOrientation="portrait"
android:value="" />
</activity>
<activity <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustPan|stateAlwaysHidden"> android:windowSoftInputMode="adjustPan|stateAlwaysHidden">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />

Binary file not shown.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 143 KiB

After

Width:  |  Height:  |  Size: 164 KiB

View File

@ -1,12 +1,15 @@
package com.example.rehabilitation.Admin.activityAdmin package com.example.rehabilitation.Admin.activityAdmin
import androidx.appcompat.app.AppCompatActivity import android.content.Intent
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import com.example.rehabilitation.R import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.databinding.ActivityFeedbackBinding import com.example.rehabilitation.databinding.ActivityFeedbackBinding
import com.example.rehabilitation.databinding.FragmentFeedbackBinding
class FeedbackActivity : AppCompatActivity() { class FeedbackActivity : AppCompatActivity() {
var backPressedTime: Long = 0
private lateinit var binding: ActivityFeedbackBinding private lateinit var binding: ActivityFeedbackBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
@ -18,5 +21,50 @@ class FeedbackActivity : AppCompatActivity() {
binding.btnExit.setOnClickListener{ binding.btnExit.setOnClickListener{
finish() finish()
} }
//Переход по ссылке на сайт
binding.txtUrlVmeda.setOnClickListener{
val i = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.vmeda.org/"))
startActivity(i)
}
//
// //Переход на почту
// binding.txtEmailDoctor.setOnClickListener{
// val intent = Intent(Intent.ACTION_SEND)
// intent.data = Uri.parse("mailto:")
// intent.type = "text/plain"
// intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(binding.txtEmailDoctor.text.toString()))// herer adresses is already string
//
// try{
// startActivity(Intent.createChooser(intent,"Choose Email Client..."))
// }
// catch (e:Exception){
// Toast.makeText(this,e.message, Toast.LENGTH_LONG).show()
// }
// }
// //Номер врача
// binding.txtNumberDoctor.setOnClickListener{
// val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + binding.txtNumberDoctor.text.toString()))
// startActivity(intent)
// }
//Номер регистратуры
binding.txtNumberRegister.setOnClickListener{
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+78122923286"))
startActivity(intent)
}
//Номер ДМС
binding.txtNumberDMS.setOnClickListener{
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "+78122923412"))
startActivity(intent)
}
}
override fun onBackPressed() {
val intetn = Intent(this, MainActivity::class.java)
startActivity(intetn)
finish()
} }
} }

View File

@ -1,12 +1,14 @@
package com.example.rehabilitation.Admin.activityAdmin package com.example.rehabilitation.Admin.activityAdmin
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle import android.os.Bundle
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.ActivityFeedbackBinding import com.example.rehabilitation.databinding.ActivityFeedbackBinding
import com.example.rehabilitation.databinding.FragmentStatisticsBinding
class StatisticsActivity : AppCompatActivity() { class StatisticsActivity : AppCompatActivity() {
var backPressedTime: Long = 0
private lateinit var binding: ActivityFeedbackBinding private lateinit var binding: ActivityFeedbackBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
@ -18,4 +20,10 @@ class StatisticsActivity : AppCompatActivity() {
finish() finish()
} }
} }
override fun onBackPressed() {
val intetn = Intent(this, MainActivity::class.java)
startActivity(intetn)
finish()
}
} }

View File

@ -1,475 +1,128 @@
package com.example.rehabilitation.Admin.activityAdmin package com.example.rehabilitation.Admin.activityAdmin
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle import android.os.Bundle
import android.util.Log
import android.view.View import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.activity.viewModels import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.asLiveData import androidx.lifecycle.asLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.example.admin.Toast.showCustomInfoToast
import com.example.admin.Toast.showCustomNiceToast
import com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor.MainSettingDoctorFragment
import com.example.rehabilitation.Auth.AuthorizationActivity
import com.example.rehabilitation.FIO
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.SettingActivity
import com.example.rehabilitation.countCategory
import com.example.rehabilitation.databinding.ActivityUserSettingBinding import com.example.rehabilitation.databinding.ActivityUserSettingBinding
import com.example.rehabilitation.db.Item import com.example.rehabilitation.Room.Item
import com.example.rehabilitation.db.ItemDaySport import com.example.rehabilitation.Room.ItemDaySport
import com.example.rehabilitation.db.ItemImage import com.example.rehabilitation.Room.ItemImage
import com.example.rehabilitation.db.ItemSportCategory import com.example.rehabilitation.Room.ItemSportCategory
import com.example.rehabilitation.db.MainDB import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.dip.Day.DayAdapter import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient
import com.example.rehabilitation.dip.Day.DayModel import com.example.rehabilitation.User.fragmentUser.HomeFragment
import com.example.rehabilitation.UserDoctorToken
import com.example.rehabilitation.counter2
import com.example.rehabilitation.model_adapter.Day.DayAdapter
import com.example.rehabilitation.model_adapter.Day.DayListModel
import com.example.rehabilitation.model_adapter.Doctor.DoctorModel
import com.example.rehabilitation.model_adapter.Edit.EditSportAdapter
import com.example.rehabilitation.model_adapter.Edit.EditSportModel
import com.example.rehabilitation.model_adapter.Image.Category.CountNameCategoryModel
import com.example.sqlitework.dip.MainViewModel import com.example.sqlitework.dip.MainViewModel
import com.example.rehabilitation.dip.Month.MonthModel import com.example.rehabilitation.model_adapter.Month.MonthModel
import com.example.rehabilitation.dip.Month.MonthAdapter import com.example.rehabilitation.model_adapter.Month.MonthAdapter
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.prefDoctor
import com.example.rehabilitation.prefFIO
import com.example.rehabilitation.prefUserDoctorToken
import com.example.rehabilitation.questionnaire_before
import com.example.rehabilitation.tokenClassDoctor
import java.time.LocalDate import java.time.LocalDate
class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapter.Listener { class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener, DayAdapter.Listener,EditSportAdapter.Listener,EditSportAdapter.ListenerEdit {
var backPressedTime: Long = 0
private lateinit var binding: ActivityUserSettingBinding private lateinit var binding: ActivityUserSettingBinding
private val model: MainViewModel by viewModels()//Инициализировали класс private val model: MainViewModel by viewModels()//Инициализировали класс
lateinit var adapterMonth: MonthAdapter lateinit var adapterMonth: MonthAdapter
lateinit var adapterDay: DayAdapter lateinit var adapterDay: DayAdapter
lateinit var editAdapter: EditSportAdapter
var loginPatient = ""
var loginDoctor = ""
var prefSport: SharedPreferences? = null
var SportUserTrue = 0
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
binding = ActivityUserSettingBinding.inflate(layoutInflater) binding = ActivityUserSettingBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
// initRcView() //Вывод фрагмента на активити при первоначальной загрузке
// initRcViewDay() supportFragmentManager.beginTransaction().replace(R.id.CLMainSettinDoctor, MainSettingDoctorFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
// model.liveListList.observe(lifeCy) {//viewLifecycleOwner - следит за циклом жизни fragment
// adapterMonth.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter)
// }
//
// model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
// adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter)
// }
//Выход prefUserDoctorToken = getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE)
binding.btnExit.setOnClickListener{ UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
prefFIO = getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
}
override fun onDestroy() {
super.onDestroy()
clearUserDoctorToken()
finish() finish()
} }
//Функция очистки данных
//Выход из добавленеия fun clearUserDoctorToken() {
binding.btnExitAdd.setOnClickListener{ val edit = prefUserDoctorToken?.edit()
binding.CLAdd.visibility = View.GONE edit?.clear()
binding.CLCreateDeleteUser.visibility = View.VISIBLE edit?.apply()
UserDoctorToken = ""
} }
//Выход из добавленеия fun saveFIO(fio: String) {
binding.btnCreate.setOnClickListener{ val edit = prefFIO?.edit()
binding.CLAdd.visibility = View.VISIBLE edit?.putString("fio", fio)
binding.CLCreateDeleteUser.visibility = View.GONE edit?.apply()
FIO = fio
}
fun clearFIO() {
val edit = prefFIO?.edit()
edit?.clear()
edit?.apply()
FIO = ""
} }
binding.cvClearDayUser.setOnClickListener{ override fun onBackPressed() {
val db = MainDB.getDB(this) val intetn = Intent(this, SettingActivity::class.java)
Thread { startActivity(intetn)
db.getDaoDaySport().deleteItemDaySport() finish()
db.getDao().deleteItem()
}.start()
}
//addListModelCards()
//addDayModelCards()
binding.btnImage.setOnClickListener{
createImageBD()
}
binding.btnCategorySport.setOnClickListener {
createSportCategory()
}
binding.btnCardC.setOnClickListener {
val db = MainDB.getDB(this)
for(i in 1..30){
val item = Item(null,
getDateTomorrow(i, "c"),//"11/11/2023",
i.toString(),
0
)
Thread {
db.getDao().insertItem(item)
}.start()
}
}
binding.btnCardB.setOnClickListener {
val db = MainDB.getDB(this)
for(i in 1..30){
val item = Item(null,
getDateTomorrow(i, "b"),//"11/11/2023",
i.toString(),
0
)
Thread {
db.getDao().insertItem(item)
}.start()
}
}
binding.btnCardJ.setOnClickListener {
val db = MainDB.getDB(this)
for(i in 1..30){
val item = Item(null,
getDateTomorrow(i, "j"),//"11/11/2023",
i.toString(),
0
)
Thread {
db.getDao().insertItem(item)
}.start()
}
}
}
private fun createImageBD() {
val db = MainDB.getDB(this)
val itemС1_1 = ItemImage(null, "${R.drawable.c1_1}", "c1","c")
val itemС1_2 = ItemImage(null, "${R.drawable.c1_2}", "c1","c")
val itemС2_1 = ItemImage(null, "${R.drawable.c2_1}", "c2","c")
val itemС2_2 = ItemImage(null, "${R.drawable.c2_2}", "c2","c")
val itemС3_1 = ItemImage(null, "${R.drawable.c3_1}", "c3","c")
val itemС3_2 = ItemImage(null, "${R.drawable.c3_2}", "c3","c")
val itemС4_1 = ItemImage(null, "${R.drawable.c4_1}", "c4","c")
val itemС4_2 = ItemImage(null, "${R.drawable.c4_1}", "c4","c")
val itemС5_1 = ItemImage(null, "${R.drawable.c5_1}", "c5","c")
val itemС5_2 = ItemImage(null, "${R.drawable.c5_2}", "c5","c")
val itemС6_1 = ItemImage(null, "${R.drawable.c6_1}", "c6","c")
val itemС6_2 = ItemImage(null, "${R.drawable.c6_2}", "c6","c")
val itemС6_3 = ItemImage(null, "${R.drawable.c6_3}", "c6","c")
val itemС7_1 = ItemImage(null, "${R.drawable.c7_1}", "c7","c")
val itemС8_1 = ItemImage(null, "${R.drawable.c8_1}", "c8","c")
val itemС8_2 = ItemImage(null, "${R.drawable.c8_2}", "c8","c")
val itemС9_1 = ItemImage(null, "${R.drawable.c9_1}", "c9","c")
val itemС9_2 = ItemImage(null, "${R.drawable.c9_2}", "c9","c")
val itemС9_3 = ItemImage(null, "${R.drawable.c9_3}", "c9","c")
val itemС10_1 = ItemImage(null, "${R.drawable.c10_1}", "c10","c")
val itemС10_2 = ItemImage(null, "${R.drawable.c10_2}", "c10","c")
val itemС10_3 = ItemImage(null, "${R.drawable.c10_3}", "c10","c")
val itemС11_1 = ItemImage(null, "${R.drawable.c11_1}", "c11","c")
val itemС12_1 = ItemImage(null, "${R.drawable.c12_1}", "c12","c")
val itemС12_2 = ItemImage(null, "${R.drawable.c12_2}", "c12","c")
val itemС13_1 = ItemImage(null, "${R.drawable.c13_1}", "c13","c")
val itemС13_2 = ItemImage(null, "${R.drawable.c13_2}", "c13","c")
val itemС14_1 = ItemImage(null, "${R.drawable.c14_1}", "c14","c")
val itemС14_2 = ItemImage(null, "${R.drawable.c14_2}", "c14","c")
val itemС15_1 = ItemImage(null, "${R.drawable.c15_1}", "c15","c")
val itemС15_2 = ItemImage(null, "${R.drawable.c15_2}", "c15","c")
val itemС16_1 = ItemImage(null, "${R.drawable.c16_1}", "c16","c")
val itemС16_2 = ItemImage(null, "${R.drawable.c16_2}", "c16","c")
val itemС17_1 = ItemImage(null, "${R.drawable.c17_1}", "c17","c")
val itemС17_2 = ItemImage(null, "${R.drawable.c17_2}", "c17","c")
val itemС18_1 = ItemImage(null, "${R.drawable.c18_1}", "c18","c")
val itemС18_2 = ItemImage(null, "${R.drawable.c18_2}", "c18","c")
val itemС18_3 = ItemImage(null, "${R.drawable.c18_3}", "c18","c")
val itemB1_1 = ItemImage(null, "${R.drawable.b1_1}", "b1", "b")
val itemB1_2 = ItemImage(null, "${R.drawable.b1_2}", "b1", "b")
val itemB2_1 = ItemImage(null, "${R.drawable.b2_1}", "b2", "b")
val itemB2_2 = ItemImage(null, "${R.drawable.b2_2}", "b2", "b")
val itemB3_1 = ItemImage(null, "${R.drawable.b3_1}", "b3", "b")
val itemB3_2 = ItemImage(null, "${R.drawable.b3_2}", "b3", "b")
val itemB3_3 = ItemImage(null, "${R.drawable.b3_3}", "b3", "b")
val itemB4_1 = ItemImage(null, "${R.drawable.b4_1}", "b4", "b")
val itemB4_2 = ItemImage(null, "${R.drawable.b4_2}", "b4", "b")
val itemJ1_1 = ItemImage(null, "${R.drawable.j1_1}", "j1","j")
val itemJ1_2 = ItemImage(null, "${R.drawable.j1_2}", "j1","j")
val itemJ2_1 = ItemImage(null, "${R.drawable.j2_1}", "j2","j")
val itemJ2_2 = ItemImage(null, "${R.drawable.j2_2}", "j2","j")
val itemJ3_1 = ItemImage(null, "${R.drawable.j3_1}", "j3","j")
val itemJ3_2 = ItemImage(null, "${R.drawable.j3_2}", "j3","j")
val itemJ4_1 = ItemImage(null, "${R.drawable.j4_1}", "j4","j")
val itemJ4_2 = ItemImage(null, "${R.drawable.j4_2}", "j4","j")
val itemJ4_3 = ItemImage(null, "${R.drawable.j4_3}", "j4","j")
val itemJ5_1 = ItemImage(null, "${R.drawable.j5_1}", "j5","j")
val itemJ6_1 = ItemImage(null, "${R.drawable.j6_1}", "j6","j")
val itemJ6_2 = ItemImage(null, "${R.drawable.j6_2}", "j6","j")
val itemJ6_3 = ItemImage(null, "${R.drawable.j6_3}", "j6","j")
val itemJ6_4 = ItemImage(null, "${R.drawable.j6_4}", "j6","j")
val itemJ7_1 = ItemImage(null, "${R.drawable.j7_1}", "j7","j")
val itemJ7_2 = ItemImage(null, "${R.drawable.j7_2}", "j7","j")
val itemJ7_3 = ItemImage(null, "${R.drawable.j7_3}", "j7","j")
val itemJ7_4 = ItemImage(null, "${R.drawable.j7_4}", "j7","j")
val itemJ7_5 = ItemImage(null, "${R.drawable.j7_5}", "j7","j")
val itemJ7_6 = ItemImage(null, "${R.drawable.j7_6}", "j7","j")
val itemJ7_7 = ItemImage(null, "${R.drawable.j7_7}", "j7","j")
val itemJ8_1 = ItemImage(null, "${R.drawable.j8_1}", "j8","j")
val itemJ8_2 = ItemImage(null, "${R.drawable.j8_2}", "j8","j")
val itemJ8_3 = ItemImage(null, "${R.drawable.j8_3}", "j8","j")
val itemJ9_1 = ItemImage(null, "${R.drawable.j9_1}", "j9","j")
val itemJ10_1 = ItemImage(null, "${R.drawable.j10_1}", "j10","j")
val itemJ10_2 = ItemImage(null, "${R.drawable.j10_2}", "j10","j")
val itemJ10_3 = ItemImage(null, "${R.drawable.j10_2}", "j10","j")
val itemJ11_1 = ItemImage(null, "${R.drawable.j11_1}", "j11","j")
val itemJ11_2 = ItemImage(null, "${R.drawable.j11_2}", "j11","j")
val itemJ11_3 = ItemImage(null, "${R.drawable.j11_3}", "j11","j")
val itemJ11_4 = ItemImage(null, "${R.drawable.j11_4}", "j11","j")
val itemJ12_1 = ItemImage(null, "${R.drawable.j12_1}", "j12","j")
val itemJ12_2 = ItemImage(null, "${R.drawable.j12_2}", "j12","j")
Thread {
db.getDaoImage().insertItemImage(itemС1_1)
db.getDaoImage().insertItemImage(itemС1_2)
db.getDaoImage().insertItemImage(itemС2_1)
db.getDaoImage().insertItemImage(itemС2_2)
db.getDaoImage().insertItemImage(itemС3_1)
db.getDaoImage().insertItemImage(itemС3_2)
db.getDaoImage().insertItemImage(itemС4_1)
db.getDaoImage().insertItemImage(itemС4_2)
db.getDaoImage().insertItemImage(itemС5_1)
db.getDaoImage().insertItemImage(itemС5_2)
db.getDaoImage().insertItemImage(itemС6_1)
db.getDaoImage().insertItemImage(itemС6_2)
db.getDaoImage().insertItemImage(itemС6_3)
db.getDaoImage().insertItemImage(itemС7_1)
db.getDaoImage().insertItemImage(itemС8_1)
db.getDaoImage().insertItemImage(itemС8_2)
db.getDaoImage().insertItemImage(itemС9_1)
db.getDaoImage().insertItemImage(itemС9_2)
db.getDaoImage().insertItemImage(itemС9_3)
db.getDaoImage().insertItemImage(itemС10_1)
db.getDaoImage().insertItemImage(itemС10_2)
db.getDaoImage().insertItemImage(itemС10_3)
db.getDaoImage().insertItemImage(itemС11_1)
db.getDaoImage().insertItemImage(itemС12_1)
db.getDaoImage().insertItemImage(itemС12_2)
db.getDaoImage().insertItemImage(itemС13_1)
db.getDaoImage().insertItemImage(itemС13_2)
db.getDaoImage().insertItemImage(itemС14_1)
db.getDaoImage().insertItemImage(itemС14_2)
db.getDaoImage().insertItemImage(itemС15_1)
db.getDaoImage().insertItemImage(itemС15_2)
db.getDaoImage().insertItemImage(itemС16_1)
db.getDaoImage().insertItemImage(itemС16_2)
db.getDaoImage().insertItemImage(itemС17_1)
db.getDaoImage().insertItemImage(itemС17_2)
db.getDaoImage().insertItemImage(itemС18_1)
db.getDaoImage().insertItemImage(itemС18_2)
db.getDaoImage().insertItemImage(itemС18_3)
db.getDaoImage().insertItemImage(itemB1_1)
db.getDaoImage().insertItemImage(itemB1_2)
db.getDaoImage().insertItemImage(itemB2_1)
db.getDaoImage().insertItemImage(itemB2_2)
db.getDaoImage().insertItemImage(itemB3_1)
db.getDaoImage().insertItemImage(itemB3_2)
db.getDaoImage().insertItemImage(itemB3_3)
db.getDaoImage().insertItemImage(itemB4_1)
db.getDaoImage().insertItemImage(itemB4_2)
db.getDaoImage().insertItemImage(itemJ1_1)
db.getDaoImage().insertItemImage(itemJ1_2)
db.getDaoImage().insertItemImage(itemJ2_1)
db.getDaoImage().insertItemImage(itemJ2_2)
db.getDaoImage().insertItemImage(itemJ3_1)
db.getDaoImage().insertItemImage(itemJ3_2)
db.getDaoImage().insertItemImage(itemJ4_1)
db.getDaoImage().insertItemImage(itemJ4_2)
db.getDaoImage().insertItemImage(itemJ4_3)
db.getDaoImage().insertItemImage(itemJ5_1)
db.getDaoImage().insertItemImage(itemJ6_1)
db.getDaoImage().insertItemImage(itemJ6_2)
db.getDaoImage().insertItemImage(itemJ6_3)
db.getDaoImage().insertItemImage(itemJ6_4)
db.getDaoImage().insertItemImage(itemJ7_1)
db.getDaoImage().insertItemImage(itemJ7_2)
db.getDaoImage().insertItemImage(itemJ7_3)
db.getDaoImage().insertItemImage(itemJ7_4)
db.getDaoImage().insertItemImage(itemJ7_5)
db.getDaoImage().insertItemImage(itemJ7_6)
db.getDaoImage().insertItemImage(itemJ7_7)
db.getDaoImage().insertItemImage(itemJ8_1)
db.getDaoImage().insertItemImage(itemJ8_2)
db.getDaoImage().insertItemImage(itemJ8_3)
db.getDaoImage().insertItemImage(itemJ9_1)
db.getDaoImage().insertItemImage(itemJ10_1)
db.getDaoImage().insertItemImage(itemJ10_2)
db.getDaoImage().insertItemImage(itemJ10_3)
db.getDaoImage().insertItemImage(itemJ11_1)
db.getDaoImage().insertItemImage(itemJ11_2)
db.getDaoImage().insertItemImage(itemJ11_3)
db.getDaoImage().insertItemImage(itemJ11_4)
db.getDaoImage().insertItemImage(itemJ12_1)
db.getDaoImage().insertItemImage(itemJ12_2)
}.start()
}
fun createSportCategory(){
getDaySport(1, C1,"c","c1")
getDaySport(2, C2,"c","c2")
getDaySport(3, C3,"c","c3")
getDaySport(4, C4,"c","c4")
getDaySport(5, C5,"c","c5")
getDaySport(6, C6,"c","c6")
getDaySport(7, C7,"c","c7")
getDaySport(8, C8,"c","c8")
getDaySport(9, C9,"c","c9")
getDaySport(10, C10,"c","c10")
getDaySport(11, C11,"c","c11")
getDaySport(12, C12,"c","c12")
getDaySport(13, C13,"c","c13")
getDaySport(14, C14,"c","c14")
getDaySport(15, C15,"c","c15")
getDaySport(16, C16,"c","c16")
getDaySport(17, C17,"c","c17")
getDaySport(18, C18,"c","c18")
getDaySport(19, B1,"b","b1")
getDaySport(20, B2,"b","b2")
getDaySport(21, B3,"b","b3")
getDaySport(22, B4,"b","b4")
getDaySport(23, J1,"j","j1" )
getDaySport(24, J2,"j","j2" )
getDaySport(25, J3,"j","j3" )
getDaySport(26, C4,"j","j4" )
getDaySport(27, J5,"j","j5" )
getDaySport(28, J6,"j","j6" )
getDaySport(29, J7,"j","j7" )
getDaySport(30, J8,"j","j8" )
getDaySport(31, J9,"j","j9" )
getDaySport(32, J10,"j","j10" )
getDaySport(33, J11,"j","j11" )
getDaySport(34, J12,"j","j12" )
}
//Заполнения модели и списка
private fun addListModelCards(){
val db = MainDB.getDB(this)
val list = ArrayList<MonthModel>()
db.getDao().getAllItems().asLiveData().observe(this){itList->
itList.forEach{
//val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}"
//binding.txtList.append(text)
val item = MonthModel(
it.id.toString(),
it.day.toString(),
it.date.toString(),
it.check.toString()
)
//model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку
list.add(item)//Передали заполненый список
}
model.liveListList.value = list
}
binding.btnSaveList.setOnClickListener{
// for(i in 1..30){
// val item = Item(null,
// getDateTomorrow(i, ),//"11/11/2023",
// 0
// )
// Thread {
// db.getDao().insertItem(item)
// }.start()
// }
}
}
fun getDaySport(i:Int, description:String, categoryImage:String, categorySport:String): String {
val db = MainDB.getDB(this)
val tomorrow = LocalDate.now().plusDays(i.toLong())
val item = ItemSportCategory(null, i.toString(), description,"3",categoryImage, categorySport)
Thread {
db.getDaoSportCategory().insertItemSportCategory(item)
}.start()
return tomorrow.toString()
}
fun getDateTomorrow(i:Int,categorySport:String): String {
val db = MainDB.getDB(this)
val DATE_PATTERN = "MM/dd/yyyy"
val tomorrow = LocalDate.now().plusDays(i.toLong())
val item = ItemDaySport(null,
tomorrow.toString(),
categorySport,
0
)
Thread {
db.getDaoDaySport().insertItemDaySport(item)
}.start()
return tomorrow.toString()
}
//Заполнения модели и списка
// private fun addDayModelCards(){
// val db = MainDB.getDB(this)
// val list = ArrayList<DayModel>()
// db.getDaoDaySport().getAllItemDaySport().asLiveData().observe(this){itList->
// itList.forEach{
// //val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}"
// //binding.txtList.append(text)
// val itemDay = DayModel(
// it.id.toString(),
// it.day.toString(),
// it.category.toString(),
// it.check.toString(),
// )
// //model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку
// list.add(itemDay)//Передали заполненый список
// }
// model.liveDayList.value = list
// }
//
// binding.btnSaveDay.setOnClickListener{
//// val item = ItemDaySport(null,
//// binding.edName.text.toString(),
//// binding.edDesc.text.toString(),
//// binding.edDayCard.text.toString(),
//// binding.edCount.text.toString(),
//// binding.edImage.text.toString(),
//// 0
//// )
//// Thread {
//// db.getDaoDaySport().insertItemDaySport(item)
//// }.start()
// }
// }
// //Инициализация списка
// private fun initRcView() = with(binding) {
// todoListRecycleView.layoutManager = GridLayoutManager(this@UserSettingActivity,1)//По вертикали будет выводить по умолчанию
// adapterMonth = MonthAdapter(this@UserSettingActivity)
// todoListRecycleView.adapter = adapterMonth
// }
//
// //Инициализация списка
// private fun initRcViewDay() = with(binding) {
// todoDayListRecycleView.layoutManager = GridLayoutManager(this@UserSettingActivity,1)//По вертикали будет выводить по умолчанию
// adapterDay = DayAdapter(this@UserSettingActivity)
// todoDayListRecycleView.adapter = adapterDay
// }
override fun onClickDay(item: DayModel) {
} }
override fun onClickExceptionOrder(item: MonthModel) { override fun onClickExceptionOrder(item: MonthModel) {
} }
//Спина //Спина
val c1 = arrayOf("c1_1", "c1_2") val c1 = arrayOf("c1_1", "c1_2")
val c2 = arrayOf("c2_1", "c2_2") val c2 = arrayOf("c2_1", "c2_2")
val c3 = arrayOf("c3_1", "c3_2") val c3 = arrayOf("c3_1", "c3_2")
val c4 = arrayOf("c4_1", "c4_2") val c4 = arrayOf("c4_1", "c4_2")
val c5 = arrayOf("c5_1", "c5_2") val c5 = arrayOf("c5_1", "c5_2")
val c6 = arrayOf("c6_1", "c6_2","c6_3") val c6 = arrayOf("c6_1", "c6_2", "c6_3")
val c7 = arrayOf("c7_1") val c7 = arrayOf("c7_1")
val c8 = arrayOf("c8_1", "c8_2") val c8 = arrayOf("c8_1", "c8_2")
val c9 = arrayOf("c9_1", "c9_2", "c9_3") val c9 = arrayOf("c9_1", "c9_2", "c9_3")
@ -527,13 +180,15 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"2-3 удерживать в напряжении;\n" + "2-3 удерживать в напряжении;\n" +
"4 - расслабиться.\n" + "4 - расслабиться.\n" +
"Повторить 6-10 раз. Дыхание произвольное. При ампутации на уровне голени можно подложить под нижнюю треть бедра валик, если есть сгибательная контрактура колена, или если пациент так лучше ощущает работу мышц.\n" "Повторить 6-10 раз. Дыхание произвольное. При ампутации на уровне голени можно подложить под нижнюю треть бедра валик, если есть сгибательная контрактура колена, или если пациент так лучше ощущает работу мышц.\n"
val C5 = "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + val C5 =
"Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" +
"Счет\n" + "Счет\n" +
"1 — опереться на ноги, поднять таз вверх;\n" + "1 — опереться на ноги, поднять таз вверх;\n" +
"2-3 — удерживать это положение;\n" + "2-3 — удерживать это положение;\n" +
"4 — опуститься в исходное положение. \n" + "4 — опуститься в исходное положение. \n" +
"Повторить 4-8 раз. Дыхание произвольное, или подъем таза осуществлять на выдохе через рот, губы сложены «трубочкой».\n" "Повторить 4-8 раз. Дыхание произвольное, или подъем таза осуществлять на выдохе через рот, губы сложены «трубочкой».\n"
val C6 = "Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" + val C6 =
"Исходное положение, руки лежат вниз вдоль туловища, под культю и под аналогичный сегмент сохранной конечности подложить мячи. \n" +
"Счет\n" + "Счет\n" +
"1 — опереться на ноги и поднять таз вверх;\n" + "1 — опереться на ноги и поднять таз вверх;\n" +
" 2 — поднять одну прямую ногу вверх на 30°—45% \n" + " 2 — поднять одну прямую ногу вверх на 30°—45% \n" +
@ -542,41 +197,48 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
val C7 = "Дыхательное упражнение — диафрагмальное дыхание. \n" + val C7 = "Дыхательное упражнение — диафрагмальное дыхание. \n" +
"Сохранную ногу поставить согнутую, вторая нога или свободно лежит на полу, или бедро закинуто на другое бедро (фото), одна ладонь лежит на животе, а другая — на груди. На вдох носом надуть животом «шарик», на выдох через рот опустить переднюю стенку живота (и втянуть ее) и расслабиться. \n" + "Сохранную ногу поставить согнутую, вторая нога или свободно лежит на полу, или бедро закинуто на другое бедро (фото), одна ладонь лежит на животе, а другая — на груди. На вдох носом надуть животом «шарик», на выдох через рот опустить переднюю стенку живота (и втянуть ее) и расслабиться. \n" +
"Повторить дыхательный цикл не более 4-6 раз. Дышать глубоко, в комфортном темпе.\n" "Повторить дыхательный цикл не более 4-6 раз. Дышать глубоко, в комфортном темпе.\n"
val C8 = "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч.\n" + val C8 =
"Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч.\n" +
"Счет\n" + "Счет\n" +
"1 упереться ногами в мяч, поднять таз вверх;\n" + "1 упереться ногами в мяч, поднять таз вверх;\n" +
"2-3 — удерживать это положение;\n" + "2-3 — удерживать это положение;\n" +
"4 - опустить таз и вернуться B исходное положение.\n" + "4 - опустить таз и вернуться B исходное положение.\n" +
"Дыхание произвольное. Повторить упражнение 6-8 раз.\n" "Дыхание произвольное. Повторить упражнение 6-8 раз.\n"
val C9 = "Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч. \n" + val C9 =
"Исходное положение, руки лежат вниз вдоль туловища, под ноги подложен большой гимнастический мяч. \n" +
"Счет\n" + "Счет\n" +
"1 - поднять таз с опорой на обе ноги;\n" + "1 - поднять таз с опорой на обе ноги;\n" +
"2 - поднять сохранную ногу вверх от опоры и остаться стоять на одной культе;\n" + "2 - поднять сохранную ногу вверх от опоры и остаться стоять на одной культе;\n" +
"3 - опустить на опору сохранную ногу;\n" + "3 - опустить на опору сохранную ногу;\n" +
"4 - опустить таз и вернуться в исходное положение. Повторить упражнение для каждой ноги по 4—6 раз. Дыхание произвольное.\n" "4 - опустить таз и вернуться в исходное положение. Повторить упражнение для каждой ноги по 4—6 раз. Дыхание произвольное.\n"
val C10 = "Исходное положение, руки лежат вниз вдоль туловища или под головой (усложненный вариант). \n" + val C10 =
"Исходное положение, руки лежат вниз вдоль туловища или под головой (усложненный вариант). \n" +
"Имитация велосипедных движений. По 6-10 движений сначала одной ногой, затем второй. Усложненный вариант упражнения (фото) — выполнение упражнения одновременно двумя ногами.\n" + "Имитация велосипедных движений. По 6-10 движений сначала одной ногой, затем второй. Усложненный вариант упражнения (фото) — выполнение упражнения одновременно двумя ногами.\n" +
"Сначала движение ногами выполняется в направлении движения вперед, а затем — назад. \n" + "Сначала движение ногами выполняется в направлении движения вперед, а затем — назад. \n" +
"Следить за дыханием и за тем, чтобы поясница была прижата к полу.\n" "Следить за дыханием и за тем, чтобы поясница была прижата к полу.\n"
val C11 = "Дыхательное упражнение — диафрагмальное дыхание.\n" + val C11 = "Дыхательное упражнение — диафрагмальное дыхание.\n" +
"Повторить дыхательный цикл не более 4-6 раз. В необходимости повторения дыхательного упражнения — ориентироваться на самочувствие пациента.\n" "Повторить дыхательный цикл не более 4-6 раз. В необходимости повторения дыхательного упражнения — ориентироваться на самочувствие пациента.\n"
val C12 = "Исходное положение, руки вытянуты перед собой, B руках — резиновая лента-амортизатор.\n" + val C12 =
"Исходное положение, руки вытянуты перед собой, B руках — резиновая лента-амортизатор.\n" +
"Счет\n" + "Счет\n" +
"1 - развести в стороны прямые руки и коснуться кулачками пола, свести лопатки;\n" + "1 - развести в стороны прямые руки и коснуться кулачками пола, свести лопатки;\n" +
"2-3 — удерживать это положение;\n" + "2-3 — удерживать это положение;\n" +
"4 — свести руки перед собой и вернуться в исходное положение.\n" + "4 — свести руки перед собой и вернуться в исходное положение.\n" +
"При выполнении упражнения акцент делать на сведение лопаток в момент растяжения резинового амортизатора.\n" "При выполнении упражнения акцент делать на сведение лопаток в момент растяжения резинового амортизатора.\n"
val C13 = "Исходное положение, в руках — резиновый амортизатор; одна рука лежит вниз вдоль туловища, вторая согнута в локте на 90° и отведена от туловища (локоть на уровне плеча), ее плечо лежит на полу. \n" + val C13 =
"Исходное положение, в руках — резиновый амортизатор; одна рука лежит вниз вдоль туловища, вторая согнута в локте на 90° и отведена от туловища (локоть на уровне плеча), ее плечо лежит на полу. \n" +
"Счет\n" + "Счет\n" +
"1 - не разгибая локтя, разворачивая лопатку, положить кисть согнутой руки на пол;\n" + "1 - не разгибая локтя, разворачивая лопатку, положить кисть согнутой руки на пол;\n" +
"2-3 — удерживать это положение;\n" + "2-3 — удерживать это положение;\n" +
"4 - вернуться в исходное положение. Повторить 10—15-20 раз. Не меняя длины хвата амортизатора, повторить с другой руки. Дыхание произвольное.\n" "4 - вернуться в исходное положение. Повторить 10—15-20 раз. Не меняя длины хвата амортизатора, повторить с другой руки. Дыхание произвольное.\n"
val C14 = "Исходное положение, поставить руки B упоре на локти, немного отведя их от туловища.\n" + val C14 =
"Исходное положение, поставить руки B упоре на локти, немного отведя их от туловища.\n" +
"1 - надавить локтями на пол, свести лопатки прогнуть грудную клетку;\n" + "1 - надавить локтями на пол, свести лопатки прогнуть грудную клетку;\n" +
"2-3 — удерживать это напряжение;\n" + "2-3 — удерживать это напряжение;\n" +
"4 - расслабиться и вернуться в исходное положение \n" + "4 - расслабиться и вернуться в исходное положение \n" +
"Повторить 4-8 раз. Дыхание ровное, без задержек.\n" "Повторить 4-8 раз. Дыхание ровное, без задержек.\n"
val C15 = "Исходное положение, на бедра надета резиновая петля, ногу со стороны ампутации ротировать внутрь (cкосолапить). \n" + val C15 =
"Исходное положение, на бедра надета резиновая петля, ногу со стороны ампутации ротировать внутрь (cкосолапить). \n" +
"Счет\n" + "Счет\n" +
"1 - скользя по поверхности, отвести ногу со стороны ампутации в сторону; \n" + "1 - скользя по поверхности, отвести ногу со стороны ампутации в сторону; \n" +
"2-3 - удерживать ногу в этом положении;\n" + "2-3 - удерживать ногу в этом положении;\n" +
@ -590,7 +252,8 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"4 - расслабиться.\n" + "4 - расслабиться.\n" +
"Повторить упражнение 10-15-20 раз. \n" + "Повторить упражнение 10-15-20 раз. \n" +
"Со временем возможно усложнение упражнения: удерживать сжатие не на счет 2-3, а на 2-3-4-5-6-7, и только на счет 8 — расслабиться. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались B напряжение, и пациент не затаивал дыхание.\n" "Со временем возможно усложнение упражнения: удерживать сжатие не на счет 2-3, а на 2-3-4-5-6-7, и только на счет 8 — расслабиться. Дыхание произвольное. Следить, чтобы мышцы плечевого пояса не вовлекались B напряжение, и пациент не затаивал дыхание.\n"
val C17 = "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель.\n" + val C17 =
"Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель.\n" +
"Счет\n" + "Счет\n" +
"1 - поднять прямую ногу на 45°; \n" + "1 - поднять прямую ногу на 45°; \n" +
"2-3 - удерживать ногу в этом положении; \n" + "2-3 - удерживать ногу в этом положении; \n" +
@ -601,7 +264,8 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"2-3-4-5-6-7 - держать ногу; \n" + "2-3-4-5-6-7 - держать ногу; \n" +
"8 - опустить ногу и вернуться в исходное положение.\n" + "8 - опустить ногу и вернуться в исходное положение.\n" +
"Со временем можно выполнять два подхода к упражнению.\n" "Со временем можно выполнять два подхода к упражнению.\n"
val C18 = "Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель. \n" + val C18 =
"Исходное положение, руки лежат под головой, на ногу со стороны ампутации надета манжета-утяжелитель. \n" +
"Счет\n" + "Счет\n" +
"1 - поднять прямую ногу на 45°;\n" + "1 - поднять прямую ногу на 45°;\n" +
"2 - согнуть ногу в бедре и колене до 90°; \n" + "2 - согнуть ногу в бедре и колене до 90°; \n" +
@ -663,7 +327,8 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"2-3 - удерживать это положение; \n" + "2-3 - удерживать это положение; \n" +
"4 — опуститься в исходное положение. \n" + "4 — опуститься в исходное положение. \n" +
"С каждой стороны повторить упражнение по 4-8 раз. Следить за дыханием.\n" "С каждой стороны повторить упражнение по 4-8 раз. Следить за дыханием.\n"
val J5 = "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под толовой. Глубокий вдох HOCOM, долгий выдох через рот, губы сложены «трубочкой». Повторить 4-6 раз.\n" val J5 =
"Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под толовой. Глубокий вдох HOCOM, долгий выдох через рот, губы сложены «трубочкой». Повторить 4-6 раз.\n"
val J6 = "Исходное положение, голова опирается на лоб. Рисуем ногой медленно букву «П».\n" + val J6 = "Исходное положение, голова опирается на лоб. Рисуем ногой медленно букву «П».\n" +
"Счет\n" + "Счет\n" +
"1 поднять прямую правую ногу вверх;\n" + "1 поднять прямую правую ногу вверх;\n" +
@ -694,17 +359,21 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"3 - развести ноги в стороны;\n" + "3 - развести ноги в стороны;\n" +
"4 - свести ноги и перекрестить их, поменяв верхнюю и нижнюю ноги.\n" + "4 - свести ноги и перекрестить их, поменяв верхнюю и нижнюю ноги.\n" +
"Упражнение сделать по 4-8 раз на каждую ногу. Следить за дыханием.\n" "Упражнение сделать по 4-8 раз на каждую ногу. Следить за дыханием.\n"
val J9 = "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под головой. Глубокий вдох носом, долгий выдох через POT, губы сложены «трубочкой». Повторить 4-6 раз.\n" val J9 =
val J10 = "Исходное положение, голова опирается на лоб, руки лежат наверху на ширине, в руках — резиновый амортизатор. \n" + "Дыхательное упражнение. Исходное положение, голова опирается на лоб, руки под головой. Глубокий вдох носом, долгий выдох через POT, губы сложены «трубочкой». Повторить 4-6 раз.\n"
val J10 =
"Исходное положение, голова опирается на лоб, руки лежат наверху на ширине, в руках — резиновый амортизатор. \n" +
"1 — поднять туловище, руки и голову вверх; \n" + "1 — поднять туловище, руки и голову вверх; \n" +
"2 — развести руки в стороны так, чтобы амортизатор лег на лопатки; \n" + "2 — развести руки в стороны так, чтобы амортизатор лег на лопатки; \n" +
"3 — свести руки наверху до ширины плеч; \n" + "3 — свести руки наверху до ширины плеч; \n" +
"4 — опуститься в исходное положение. \n" + "4 — опуститься в исходное положение. \n" +
"Повторить упражнение 6-10 раз. Дыхание произвольное.\n" + "Повторить упражнение 6-10 раз. Дыхание произвольное.\n" +
" Со временем можно усложнить упражнение: разводить руки в стороны не один раз, а несколько раз подряд; также можно сделать паузу в момент, когда руки разведены в стороны. Дыхание произвольное. Можно одновременно с подъемом туловища поднимать поочередно то одну, то вторую ногу.\n" " Со временем можно усложнить упражнение: разводить руки в стороны не один раз, а несколько раз подряд; также можно сделать паузу в момент, когда руки разведены в стороны. Дыхание произвольное. Можно одновременно с подъемом туловища поднимать поочередно то одну, то вторую ногу.\n"
val J11 = "Исходное положение, руки под головой. Поднять плечевой пояс и согнутые к плечам руки. Имитация плавания брассом. Дыхание ровное. \n" + val J11 =
"Исходное положение, руки под головой. Поднять плечевой пояс и согнутые к плечам руки. Имитация плавания брассом. Дыхание ровное. \n" +
"Два подхода по 10-15-20 движений. Следить за полным выпрямлением рук наверх, разведением прямых рук B стороны, сведением лопаток B момент приведения плеч, а также за тем, чтобы корпус при выпрямлении рук наверх не опускался. Дыхание произвольное.\n" "Два подхода по 10-15-20 движений. Следить за полным выпрямлением рук наверх, разведением прямых рук B стороны, сведением лопаток B момент приведения плеч, а также за тем, чтобы корпус при выпрямлении рук наверх не опускался. Дыхание произвольное.\n"
val J12 = "Исходное положение, руки лежат под головой, голова опирается на лоб. На ноге со стороны ампутации надета манжета с утяжелителем.\n" + val J12 =
"Исходное положение, руки лежат под головой, голова опирается на лоб. На ноге со стороны ампутации надета манжета с утяжелителем.\n" +
"Счет\n" + "Счет\n" +
"1 - поднять ногу с утяжелителем;\n" + "1 - поднять ногу с утяжелителем;\n" +
"2-3 — удерживать ногу; \n" + "2-3 — удерживать ногу; \n" +
@ -713,6 +382,17 @@ class UserSettingActivity : AppCompatActivity(), MonthAdapter.Listener,DayAdapte
"Усложнение: можно на счет 2 - отвести ногу в сторону, на счет 3 - вернуть ногу к центру, счет 4 — опуститься в исходное положение. Также можно отводить в сторону не один раз, а несколько раз подряд. Дыхание свободное. \n" + "Усложнение: можно на счет 2 - отвести ногу в сторону, на счет 3 - вернуть ногу к центру, счет 4 — опуститься в исходное положение. Также можно отводить в сторону не один раз, а несколько раз подряд. Дыхание свободное. \n" +
"Со временем все упражнения можно выполнять с утяжелителем." "Со временем все упражнения можно выполнять с утяжелителем."
override fun onClickDay(item: DayListModel) {
}
override fun onClickExceptionOrder(item: EditSportModel) {
}
override fun onClickEditCard(item: EditSportModel) {
TODO("Not yet implemented")
}
} }

View File

@ -1,26 +0,0 @@
package com.example.rehabilitation.Admin.fragmrntAdmin
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentFeedbackBinding
class FeedbackFragment : Fragment() {
private lateinit var binding: FragmentFeedbackBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentFeedbackBinding.inflate(layoutInflater, container,false)
return inflater.inflate(R.layout.fragment_feedback, container, false)
}
companion object {
fun newInstance() = FeedbackFragment()
}
}

View File

@ -1,49 +0,0 @@
package com.example.rehabilitation.Admin.fragmrntAdmin
import android.os.Binder
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentMainSettingBinding
class MainSettingFragment : Fragment() {
private lateinit var binding: FragmentMainSettingBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainSettingBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Выход на основную часть
binding.btnExitSetting.setOnClickListener {
activity?.finish()
}
binding.cvSettingUser.setOnClickListener{
}
binding.cvFeedback.setOnClickListener{
}
binding.cvStatistics.setOnClickListener{
}
}
companion object {
fun newInstance() = MainSettingFragment()
}
}

View File

@ -0,0 +1,503 @@
package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor
import android.content.Context
import android.os.Binder
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomInfoToast
import com.example.admin.Toast.showCustomNiceToast
import com.example.rehabilitation.Block
import com.example.rehabilitation.CursDayNull
import com.example.rehabilitation.DayAfter
import com.example.rehabilitation.DayBefore
import com.example.rehabilitation.EmailPatient
import com.example.rehabilitation.FIO
import com.example.rehabilitation.PatientDoctorNew
import com.example.rehabilitation.PauseDay
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient
import com.example.rehabilitation.SportCursDay
import com.example.rehabilitation.SportCursDayDangerAfter
import com.example.rehabilitation.SportCursDayDangerBefore
import com.example.rehabilitation.SportCursDayNumber
import com.example.rehabilitation.SportDateStart
import com.example.rehabilitation.SportMaxCount
import com.example.rehabilitation.SportPlusCount
import com.example.rehabilitation.SportUserTrue
import com.example.rehabilitation.UserPatientToken
import com.example.rehabilitation.databinding.FragmentCreatePatientBinding
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.prefBlock
import com.example.rehabilitation.prefCursDangerDayAfter
import com.example.rehabilitation.prefCursDangerDayBefore
import com.example.rehabilitation.prefCursDay
import com.example.rehabilitation.prefCursDayNull
import com.example.rehabilitation.prefDayAfter
import com.example.rehabilitation.prefDayBefore
import com.example.rehabilitation.prefEmailPatient
import com.example.rehabilitation.prefFIO
import com.example.rehabilitation.prefPatientDoctorNew
import com.example.rehabilitation.prefPauseDay
import com.example.rehabilitation.prefSport
import com.example.rehabilitation.prefSportCursDayNumber
import com.example.rehabilitation.prefSportDateStart
import com.example.rehabilitation.prefSportMaxCount
import com.example.rehabilitation.prefSportPlusCount
import com.example.rehabilitation.prefUserPatientToken
import com.example.sqlitework.dip.MainViewModel
class CreatePatientFragment : Fragment() {
private lateinit var binding: FragmentCreatePatientBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
var addSave = 0
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCreatePatientBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//Выход из создания пациента
binding.btnBackCreatePatient.setOnClickListener {
visible3()
}
createBtnPatient()
deleteBtnPatient()
liveLookPatientCurrent()
prefUserPatientToken = activity?.getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE)
UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE)
EmailPatient = prefEmailPatient?.getString("emailPatient", "")!!
prefSport = activity?.getSharedPreferences("SportUserTrue", Context.MODE_PRIVATE)
SportUserTrue = prefSport?.getInt("spt", 0)!!
//Какой сегодня курс
prefSportCursDayNumber = activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE)
SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!!
prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE)
SportCursDay = prefCursDay?.getInt("scd", 0)!!
prefCursDangerDayBefore = activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE)
SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!!
prefCursDangerDayAfter = activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE)
SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!!
prefCursDayNull = activity?.getSharedPreferences("CursDayNull", Context.MODE_PRIVATE)
CursDayNull = prefCursDayNull?.getString("cdn", "")!!
//Для пауз и блоков
prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE)
PauseDay = prefPauseDay?.getString("pd", "")!!
prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE)
Block = prefBlock?.getString("b", "")!!
//ДАнные пациента
prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
//Дата старта тренировки
prefSportDateStart = activity?.getSharedPreferences("SportDateStart", Context.MODE_PRIVATE)
SportDateStart = prefSportDateStart?.getString("sportdatestart", "")!!
//Есть ли аакаунт у пациента
prefPatientDoctorNew = activity?.getSharedPreferences("PatientDoctorNew", Context.MODE_PRIVATE)
PatientDoctorNew = prefPatientDoctorNew?.getInt("patientdoctornew", 0)!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
}
fun savePatientDoctorNew(patientdoctornew: Int) {
val edit = prefPatientDoctorNew?.edit()
edit?.putInt("patientdoctornew", patientdoctornew)
edit?.apply()
PatientDoctorNew = patientdoctornew
}
fun clearPatientDoctorNew() {
val edit = prefPatientDoctorNew?.edit()
edit?.clear()
edit?.apply()
PatientDoctorNew = 0
}
fun saveFIO(fio: String) {
val edit = prefFIO?.edit()
edit?.putString("fio", fio)
edit?.apply()
FIO = fio
}
fun clearFIO() {
val edit = prefFIO?.edit()
edit?.clear()
edit?.apply()
FIO = ""
}
fun saveEmailPatient(emailPatient: String) {
val edit = prefEmailPatient?.edit()
edit?.putString("emailPatient", emailPatient)
edit?.apply()
EmailPatient = emailPatient
}
fun clearEmailPatient() {
val edit = prefEmailPatient?.edit()
edit?.clear()
edit?.apply()
EmailPatient = ""
}
//Экран о пациенте
fun visible3() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit()
}
//Диалоговое окно
private fun createAlеrtDialogCreate(
nameCreate: String,
surnameCreate: String,
//patronymicCreate: String,
diagnosisCreate: String,
//emailCreate: String,
loginCreate: String,
passwordCreate: String
) {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Создание")
builder.setMessage("Вы уверены что хотите создать пользователя")
builder.setNegativeButton("Назад") { dialogInterface, i ->
}
builder.setPositiveButton("Подтвердить") { dialogInterface, i ->
createPatient(
nameCreate,
surnameCreate,
//patronymicCreate,
diagnosisCreate,
//emailCreate,
loginCreate,
passwordCreate
)
}
builder.show()
}
//Создание нового пациента
private fun createPatient(
nameCreate: String,
surnameCreate: String,
//patronymicCreate: String,
diagnosisCreate: String,
//emailCreate: String,
loginCreate: String,
passwordCreate: String
) {
val db = MainDB.getDB(requireContext())
val item = ItemPatient(
null,
nameCreate,
surnameCreate,
"",
diagnosisCreate,
//emailCreate,
0,
loginCreate,
passwordCreate,
)
Thread {
db.getDaoPatient().insertItemPatient(item)
}.start()
visible3()
savePatientDoctorNew(1)
clearPatientED()
Toast(requireContext()).showCustomNiceToast("Пользователь создан", requireActivity())
//Сохраняем то что пациент создан
}
//Функция для очистки полей
private fun clearPatientED() = with(binding) {
edCreateName.setText("")
edCreateSurname.setText("")
edDiagnosis.setText("")
edCreateEmail.setText("")
edCreateLogin.setText("")
edCreatePassword.setText("")
}
//Удаление определенного пациента
private fun deleteBtnPatient() = with(binding) {
binding.btnDeletePatient.setOnClickListener {
createAlеrtDialogDelete()
}
}
private fun createAlеrtDialogDelete() {
val db = MainDB.getDB(requireContext())
val edException = EditText(requireContext())
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Удаление")
builder.setMessage("Введите login пользователя для удаления")
builder.setView(edException)
builder.setNegativeButton("Назад") { dialogInterface, i ->
}
builder.setPositiveButton("Подтвердить") { dialogInterface, i ->
if(EmailPatient == edException.text.toString()){
deletePatient(edException.text.toString())
clearFIO()
clearEmailPatient()
clearDate()
clearSportCursDay()
clearSportCursDayDangerBefore()
clearSportCursDayDangerAfter()
clearPauseDay()
clearBlock()
clearDayBefore()
clearDayAfter()
clearSportPlusCount()
clearSportMaxCount()
clearSportDateStart()
clearCursDayNumber()
//Сохраняем то что пациент создан
clearPatientDoctorNew()
clearUserPatientToken()
Thread {
db.getDaoDaySport().deleteItemDaySport()
db.getDao().deleteItem()
db.getDaoQB().deleteBQ()
db.getDaoQA().deleteAQ()
}.start()
}
else{
Toast(requireContext()).showCustomInfoToast("Такого пользователя нету", requireActivity())
}
}
builder.show()
}
//Функция удаления пользователя
private fun deletePatient(login: String) {
val db = MainDB.getDB(requireContext())
Thread {
db.getDaoPatient().deletePatient(login)
}.start()
Toast(requireContext()).showCustomInfoToast("Аккаунт пациента был удален", requireActivity())
}
//Создание пациеанта
private fun createBtnPatient() {
binding.btnSaveCreatePatient.setOnClickListener {
addSave = 1
val db = MainDB.getDB(requireContext())
db.getDaoPatient().getAllItemPatient().asLiveData().observe(requireActivity()){
val listPatient = it.size
if(listPatient == 0){
val item = PatientModel(
"",
"",
"",
"",
"",
"",
"",
"",
)
model.liveLookPatientCurrent.value = item
}
else{
it.forEach(){
val item = PatientModel(
it.id.toString(),
"",
"",
"",
"",
"",
"",
"",
)
model.liveLookPatientCurrent.value = item
}
}
}
}
}
private fun liveLookPatientCurrent() = with(binding) {
model.liveLookPatientCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
if(addSave == 1){
Log.d("id","id123 = ${it.id}")
if(it.id != "" || it.id == null || it.id.isNotBlank()){
Toast(requireContext()).showCustomInfoToast("Аккаунт присутсвует", requireActivity())
}
else{
val nameCreate = binding.edCreateName.text.toString()
val surnameCreate = binding.edCreateSurname.text.toString()
val diagnosisCreate = binding.edDiagnosis.text.toString()
val emailCreate = binding.edCreateEmail.text.toString()
val loginCreate = binding.edCreateLogin.text.toString()
val passwordCreate = binding.edCreatePassword.text.toString()
if (nameCreate != "" && surnameCreate != "" && diagnosisCreate != "" && loginCreate != "" && passwordCreate != "") {
createAlеrtDialogCreate(
nameCreate,
surnameCreate,
//patronymicCreate,
diagnosisCreate,
//emailCreate,
loginCreate,
passwordCreate
)
saveFIO(surnameCreate+" "+nameCreate)
saveEmailPatient(loginCreate)
} else {
Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity())
}
}
//Сбрасываем нажатие
addSave=0
}
}
}
fun clearUserPatientToken() {
val edit = prefUserPatientToken?.edit()
edit?.clear()
edit?.apply()
UserPatientToken = ""
}
fun clearCursDayNumber() {
val edit = prefSportCursDayNumber?.edit()
edit?.clear()
edit?.apply()
SportCursDayNumber = 0
}
fun clearSportDateStart() {
val edit = prefSportDateStart?.edit()
edit?.clear()
edit?.apply()
SportDateStart = "0"
}
fun clearSportPlusCount() {
val edit = prefSportPlusCount?.edit()
edit?.clear()
edit?.apply()
SportPlusCount = 0
}
fun clearSportMaxCount() {
val edit = prefSportMaxCount?.edit()
edit?.clear()
edit?.apply()
SportMaxCount = 0
}
fun clearDayBefore() {
val edit = prefDayBefore?.edit()
edit?.clear()
edit?.apply()
DayBefore = ""
}
fun clearDayAfter() {
val edit = prefDayAfter?.edit()
edit?.clear()
edit?.apply()
DayAfter = ""
}
fun clearBlock() {
val edit = prefBlock?.edit()
edit?.clear()
edit?.apply()
Block = ""
}
fun clearPauseDay() {
val edit = prefPauseDay?.edit()
edit?.clear()
edit?.apply()
PauseDay = ""
}
fun clearDate() {
val edit = prefSport?.edit()
edit?.clear()
edit?.apply()
SportUserTrue = 0
}
fun clearSportCursDay() {
val edit = prefCursDay?.edit()
edit?.clear()
edit?.apply()
SportCursDay = 0
}
fun clearSportCursDayDangerBefore() {
val edit = prefCursDangerDayBefore?.edit()
edit?.clear()
edit?.apply()
SportCursDayDangerBefore = 0
}
fun clearSportCursDayDangerAfter() {
val edit = prefCursDangerDayAfter?.edit()
edit?.clear()
edit?.apply()
SportCursDayDangerAfter = 0
}
companion object {
fun newInstance() = CreatePatientFragment()
}
}

View File

@ -0,0 +1,219 @@
package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor
import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomInfoToast
import com.example.admin.Toast.showCustomNiceToast
import com.example.rehabilitation.DayBefore
import com.example.rehabilitation.EmailPatient
import com.example.rehabilitation.FIO
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.SportCursDayDangerBefore
import com.example.rehabilitation.databinding.FragmentEditPatientBinding
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.prefCursDangerDayBefore
import com.example.rehabilitation.prefDayBefore
import com.example.rehabilitation.prefEmailPatient
import com.example.rehabilitation.prefFIO
import com.example.sqlitework.dip.MainViewModel
class EditPatientFragment : Fragment() {
private lateinit var binding: FragmentEditPatientBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
var loginPatient = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentEditPatientBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
enabledPatient()
editBtnSavePatient()
liveSettingPatientCurrent()
outputOfDataParient()
//Выход из редактирвоания данных пациента
binding.btnBackPatientSetting.setOnClickListener {
visible3()
}
prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE)
EmailPatient = prefEmailPatient?.getString("emailPatient", "")!!
}
override fun onResume() {
super.onResume()
}
fun saveFIO(fio: String) {
val edit = prefFIO?.edit()
edit?.putString("fio", fio)
edit?.apply()
FIO = fio
}
fun clearFIO() {
val edit = prefFIO?.edit()
edit?.clear()
edit?.apply()
FIO = ""
}
fun saveEmailPatient(emailPatient: String) {
val edit = prefEmailPatient?.edit()
edit?.putString("emailPatient", emailPatient)
edit?.apply()
EmailPatient = emailPatient
}
fun clearEmailPatient() {
val edit = prefEmailPatient?.edit()
edit?.clear()
edit?.apply()
EmailPatient = ""
}
//Экран о пациенте
fun visible3() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit()
}
//Функция отключающая поля для ввода редактирования пациента
private fun enabledPatient() = with(binding) {
edEditNamePatient.setEnabled(false)
edEditSurnamePatient.setEnabled(false)
//edEditPatronymicPatient.setEnabled(false)
edEditDiagnosisPatient.setEnabled(false)
edEditLoginPatient.setEnabled(false)
//edEditEmailPatient.setEnabled(false)
edEditPasswordPatient.setEnabled(false)
enabledPatientBtn()
}
//Функция активации полей при редактирование пациента
private fun enabledPatientBtn() = with(binding) {
btnEditNamePatient.setOnClickListener { edEditNamePatient.setEnabled(true) }
btnEditSurnamePatient.setOnClickListener { edEditSurnamePatient.setEnabled(true) }
//btnEditPatronymicPatient.setOnClickListener { edEditPatronymicPatient.setEnabled(true) }
btnEditDiagnosisPatient.setOnClickListener { edEditDiagnosisPatient.setEnabled(true) }
btnEditLoginPatient.setOnClickListener { edEditLoginPatient.setEnabled(true) }
//btnEditEmailPatient.setOnClickListener { edEditEmailPatient.setEnabled(true) }
btnEditPasswordPatient.setOnClickListener { edEditPasswordPatient.setEnabled(true) }
}
//Сохранение измененных данных для пациента
private fun editBtnSavePatient() = with(binding) {
binding.btnSaveEditPatient.setOnClickListener {
val name = edEditNamePatient.text.toString()
val surname = edEditSurnamePatient.text.toString()
// val patronymic = edEditPatronymicPatient.text.toString()
val diagnosis = edEditDiagnosisPatient.text.toString()
val login = edEditLoginPatient.text.toString()
//val email = edEditEmailPatient.text.toString()
val password = edEditPasswordPatient.text.toString()
if (name != "" && surname != "" && login != "" && password != "" && diagnosis != "") {
saveFIO(surname +" "+ name)
saveEmailPatient(login)
val db = MainDB.getDB(requireContext())
Thread {
db.getDaoPatient().updatePatient(
loginPatient,
name,
surname,
"",
diagnosis,
login,
password
)
}.start()
Toast(requireContext()).showCustomNiceToast(
"Данные обновлены",
requireActivity()
)
} else {
Toast(requireContext()).showCustomInfoToast(
"Не все поля заполнены",
requireActivity()
)
}
}
}
private fun liveSettingPatientCurrent() = with(binding) {
model.liveSettingPatientCurrent.observe(viewLifecycleOwner) {
//viewLifecycleOwner - следит за циклом жизни fragment
Log.i("liveSettingPatientCurrent","liveSettingPatientCurrent")
binding.edEditNamePatient.setText(it.name)
binding.edEditSurnamePatient.setText(it.surname)
//binding.edEditPatronymicPatient.setText(it.patronymic)
binding.edEditDiagnosisPatient.setText(it.diagnosis)
//binding.edEditEmailPatient.setText("")
binding.edEditLoginPatient.setText(it.login)
binding.edEditPasswordPatient.setText(it.password)
loginPatient = it.login
visible5()
}
}
//Экран редактировани данных пациента
fun visible5() {
Log.i("visible5","visible5")
binding.CLLoad.visibility = View.GONE
binding.CLEditPatien.visibility = View.VISIBLE
}
private fun outputOfDataParient() {
Log.i("outputOfDataParient","outputOfDataParient")
visibleLoad()
val db = MainDB.getDB(requireContext())
db.getDaoPatient().getAuthItemPatientOutput(EmailPatient).asLiveData().observe(requireActivity()) { itList ->
itList.forEach {
val item = PatientModel(
it.id.toString(),
it.name.toString(),
it.surname.toString(),
it.patronymic.toString(),
it.diagnosis.toString(),
it.number_of_courses.toString(),
it.login.toString(),
it.password.toString(),
)
model.liveSettingPatientCurrent.value = item
}
}
}
//Экран создания пациенат
fun visibleLoad() {
binding.CLLoad.visibility = View.VISIBLE
binding.CLEditPatien.visibility = View.GONE
}
companion object {
fun newInstance() = EditPatientFragment()
}
}

View File

@ -0,0 +1,153 @@
package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomInfoToast
import com.example.admin.Toast.showCustomNiceToast
import com.example.rehabilitation.EmailPatient
import com.example.rehabilitation.FIO
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.databinding.FragmentMainPatientBinding
import com.example.rehabilitation.fragment.InfoFragment.MedicalReabilitationFragment
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.prefEmailPatient
import com.example.rehabilitation.prefFIO
class MainPatientFragment : Fragment()/*, MainActivity.IOnBackPressed*/ {
private lateinit var binding: FragmentMainPatientBinding
// override fun onBackPressed(): Boolean {
// return if (true) {
// Toast(requireContext()).showCustomInfoToast("123123213", requireActivity())
// true
// } else {
// false
// }
// }
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainPatientBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE)
EmailPatient = prefEmailPatient?.getString("emailPatient", "")!!
//Выход из мею настроек пациента
binding.btnExitMainPAtient.setOnClickListener {
visible1()
}
binding.btnSportPatient.setOnClickListener {
if(FIO !=""){
visible4()
}
else{
Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity())
}
}
binding.btnCreatePatient.setOnClickListener {
visible7()
}
binding.btnEditPatient.setOnClickListener {
if(FIO !=""){
visible5()
}
else{
Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity())
}
}
}
// override fun onBackPressed(): Boolean {
// return if (myCondition) {
// //action not popBackStack
// true
// } else {
// false
// }
// }
fun saveFIO(fio: String) {
val edit = prefFIO?.edit()
edit?.putString("fio", fio)
edit?.apply()
FIO = fio
}
fun clearFIO() {
val edit = prefFIO?.edit()
edit?.clear()
edit?.apply()
FIO = ""
}
fun saveEmailPatient(emailPatient: String) {
val edit = prefEmailPatient?.edit()
edit?.putString("emailPatient", emailPatient)
edit?.apply()
EmailPatient = emailPatient
}
fun clearEmailPatient() {
val edit = prefEmailPatient?.edit()
edit?.clear()
edit?.apply()
EmailPatient = ""
}
//Экран создания пациенат
fun visibleLoad() {
binding.CLLoad.visibility = View.VISIBLE
binding.CLMainPatient.visibility = View.GONE
}
//Основной экран
fun visible1() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainSettingDoctorFragment.newInstance())?.addToBackStack(null)?.commit()
}
//Экран тренировок пациента
fun visible4() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,PatientSportFragment.newInstance())?.addToBackStack(null)?.commit()
// val infoFrag = activity?.supportFragmentManager?.beginTransaction()
// infoFrag?.replace(R.id.CLMainSettinDoctor, PatientSportFragment.newInstance())
// infoFrag?.addToBackStack(null)
// infoFrag?.commit()
}
//Экран редактировани данных пациента
fun visible5() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,EditPatientFragment.newInstance())?.addToBackStack(null)?.commit()
}
//Экран создания пациенат
fun visible7() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,CreatePatientFragment.newInstance())?.addToBackStack(null)?.commit()
}
companion object {
fun newInstance() = MainPatientFragment()
}
}

View File

@ -0,0 +1,336 @@
package com.example.rehabilitation.Admin.fragmrntAdmin.SettingDoctor
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomInfoToast
import com.example.rehabilitation.Auth.AuthDoctorActivity
import com.example.rehabilitation.Auth.AuthorizationActivity
import com.example.rehabilitation.Block
import com.example.rehabilitation.EmailPatient
import com.example.rehabilitation.FIO
import com.example.rehabilitation.PauseDay
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.SettingActivity
import com.example.rehabilitation.SportDateStart
import com.example.rehabilitation.SportPlusCount
import com.example.rehabilitation.User.fragmentUser.SceduleFragment
import com.example.rehabilitation.UserDoctorToken
import com.example.rehabilitation.counter2
import com.example.rehabilitation.databinding.FragmentMainSettingDoctorBinding
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.prefBlock
import com.example.rehabilitation.prefDoctor
import com.example.rehabilitation.prefEmailPatient
import com.example.rehabilitation.prefFIO
import com.example.rehabilitation.prefPauseDay
import com.example.rehabilitation.prefSportDateStart
import com.example.rehabilitation.prefUserDoctorToken
import com.example.rehabilitation.tokenClassDoctor
import com.example.sqlitework.dip.MainViewModel
import java.time.LocalDate
class MainSettingDoctorFragment : Fragment() {
private lateinit var binding: FragmentMainSettingDoctorBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
private var addPatient = false
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMainSettingDoctorBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
prefFIO = activity?.getSharedPreferences("FIO", Context.MODE_PRIVATE)
FIO = prefFIO?.getString("fio", "")!!
prefEmailPatient = activity?.getSharedPreferences("EmailPatient", Context.MODE_PRIVATE)
EmailPatient = prefEmailPatient?.getString("emailPatient", "")!!
prefSportDateStart = activity?.getSharedPreferences("SportDateStart", Context.MODE_PRIVATE)
SportDateStart = prefSportDateStart?.getString("sportdatestart", "")!!
//Для пауз и блоков
prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE)
PauseDay = prefPauseDay?.getString("pd", "")!!
prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE)
Block = prefBlock?.getString("b", "")!!
data_prefDoctorPatientToken()
//Вызываем вывод данных пациента
outputOfDataPatient()
//Получаем данные пациента
liveSettingPatientCurrent()
binding.btnPatient.setOnClickListener {
visible3()
}
//Выход из раздела врача
binding.btnExitDoctorProfil.setOnClickListener {
clearUserDoctorToken()
val intetn = Intent(requireContext(), SettingActivity::class.java)
activity?.finish()
startActivity(intetn)
}
//Выход из аккаунта врача
binding.btnExitAuthDoctor.setOnClickListener {
createAlеrtDialogExitAuth()
}
if(SportDateStart !=""){
binding.txtDateSport.setText("Дата назначения: ${SportDateStart}")
binding.cardViewSportDay.setCardBackgroundColor(Color.parseColor("#9CD57E"))
}
else{
binding.txtDateSport.setText("Курс отсуствует")
binding.cardViewSportDay.setCardBackgroundColor(Color.parseColor("#D57E7E"))
}
if(FIO ==""){
visibleLoad()
binding.txtSurname.setText("")
binding.txtName.setText("")
binding.txtPatronymic.setText("")
binding.txtEmail.setText("")
binding.txtDiagnoz.setText("")
}
//Цвет кнопок в зависимоти паузы и блока
colorBtnBlockPause()
binding.cardViewBan.setOnClickListener {
if(FIO !=""){
if(Block <= LocalDate.now().toString() || Block == ""){
saveBlock(LocalDate.now().plusDays(3).toString())
Toast(requireContext()).showCustomInfoToast("Курс заблокирован", requireActivity())
binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#FF3F3F"))
}
else{
clearBlock()
Toast(requireContext()).showCustomInfoToast("Курс разблокирован", requireActivity())
binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#8FF174"))
}
}
else{
Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity())
}
}
binding.cardViewPause.setOnClickListener {
if(FIO !=""){
if(PauseDay <= LocalDate.now().toString() || PauseDay == ""){
savePauseDay(LocalDate.now().plusDays(1).toString())
Toast(requireContext()).showCustomInfoToast("Пауза на 3 дня", requireActivity())
binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#FF3F3F"))
}
else{
clearPauseDay()
Toast(requireContext()).showCustomInfoToast("Пауза снята", requireActivity())
binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#8FF174"))
}
}
else{
Toast(requireContext()).showCustomInfoToast("Создайте аккаунт пациенту", requireActivity())
}
}
}
private fun colorBtnBlockPause() {
//Цвет кнопки в зависимоти от включен ли блок
if(Block==""){
binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#8FF174"))
}
else{
binding.cardViewBan.setCardBackgroundColor(Color.parseColor("#FF3F3F"))
}
//Цвет кнопки в зависимоти от включена ли пацза
if(PauseDay==""){
binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#8FF174"))
}
else{
binding.cardViewPause.setCardBackgroundColor(Color.parseColor("#FF3F3F"))
}
}
fun saveBlock(b: String) {
val edit = prefBlock?.edit()
edit?.putString("b", b)
edit?.apply()
Block = b
}
fun clearBlock() {
val edit = prefBlock?.edit()
edit?.clear()
edit?.apply()
SportPlusCount = 0
}
fun savePauseDay(pd: String) {
val edit = prefPauseDay?.edit()
edit?.putString("pd", pd)
edit?.apply()
PauseDay = pd
}
fun clearPauseDay() {
val edit = prefPauseDay?.edit()
edit?.clear()
edit?.apply()
PauseDay = ""
}
override fun onDestroy() {
super.onDestroy()
clearUserDoctorToken()
}
override fun onResume() {
super.onResume()
if(FIO ==""){
visibleLoad()
binding.txtSurname.setText("")
binding.txtName.setText("")
binding.txtPatronymic.setText("")
binding.txtEmail.setText("")
binding.txtDiagnoz.setText("")
}
//Цвет кнопок в зависимоти паузы и блока
colorBtnBlockPause()
}
//Диалоговое окно
private fun createAlеrtDialogExitAuth() {
val builder = AlertDialog.Builder(requireContext())
builder.setTitle("Выход")
builder.setMessage("Вы уверены что хотите выйти из аккаунта")
builder.setNegativeButton("Назад") { dialogInterface, i ->
}
builder.setPositiveButton("Подтвердить") { dialogInterface, i ->
clearUserDoctorToken()
val intetn = Intent(requireContext(), SettingActivity::class.java)
activity?.finish()
startActivity(intetn)
}
builder.show()
}
//Фиксируем токен врача
private fun data_prefDoctorPatientToken() {
prefUserDoctorToken = activity?.getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE)
UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
if(UserDoctorToken == ""){
val intetn = Intent(requireContext(), AuthDoctorActivity::class.java)
activity?.finish()
startActivity(intetn)
}
}
//Записываем число
fun saveUserDoctorToken(userdoctortoken: String) {
val editer = prefUserDoctorToken?.edit()
editer?.putString("userdoctortoken", userdoctortoken)
editer?.apply()
UserDoctorToken = userdoctortoken
}
//Функция очистки данных
fun clearUserDoctorToken() {
val edit = prefUserDoctorToken?.edit()
edit?.clear()
edit?.apply()
UserDoctorToken = ""
}
//Получение из базы данных пациента
private fun outputOfDataPatient() {
Log.i("111","111")
visibleLoad()
Log.i("122","122")
val db = MainDB.getDB(requireContext())
db.getDaoPatient().getAuthItemPatientOutput(EmailPatient).asLiveData().observe(requireActivity()) { itList ->
itList.forEach {
val item = PatientModel(
it.id.toString(),
it.name,
it.surname,
it.patronymic,
it.diagnosis,
it.number_of_courses.toString(),
it.login,
it.password,
)
model.liveSettingPatientCurrent.value = item
}
}
}
//ВЫводим данные пациента
private fun liveSettingPatientCurrent() = with(binding) {
model.liveSettingPatientCurrent.observe(viewLifecycleOwner) {
Log.i("333","333")
binding.txtSurname.setText(it.surname)
binding.txtName.setText(it.name)
binding.txtPatronymic.setText(it.patronymic)
binding.txtEmail.setText(it.login)
binding.txtDiagnoz.setText(it.diagnosis)
visible5()
}
}
//Экран загрузки
fun visibleLoad() {
Log.i("222","222")
binding.cardLoad.visibility = View.VISIBLE
binding.CLMainSetting.visibility = View.VISIBLE
}
//Экран с данными пациента и кнопками
fun visible5() {
Log.i("444","444")
binding.cardLoad.visibility = View.GONE
binding.CLMainSetting.visibility = View.VISIBLE
}
//Экран о пациенте
fun visible3() {
activity?.supportFragmentManager?.beginTransaction()?.replace(R.id.CLMainSettinDoctor,MainPatientFragment.newInstance())?.addToBackStack(null)?.commit()
}
companion object {
fun newInstance() = MainSettingDoctorFragment()
}
}

View File

@ -1,32 +0,0 @@
package com.example.rehabilitation.Admin.fragmrntAdmin
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentStatisticsBinding
class StatisticsFragment : Fragment() {
private lateinit var binding: FragmentStatisticsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentStatisticsBinding.inflate(layoutInflater, container,false)
return binding.root
//ТУТ БОЛЬШЕ НИЧЕГО НЕ ТРОГАЙ
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//ВОТ ТУТ ТЫ ВСТАВЛЯЕШЬ КОД
}
companion object {
fun newInstance() = StatisticsFragment()
}
}

View File

@ -1,26 +0,0 @@
package com.example.rehabilitation.Admin.fragmrntAdmin
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentUserSettingBinding
class UserSettingFragment : Fragment() {
private lateinit var binding: FragmentUserSettingBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentUserSettingBinding.inflate(layoutInflater,container,false)
return binding.root
}
companion object {
fun newInstance() = UserSettingFragment()
}
}

View File

@ -0,0 +1,29 @@
package com.example.rehabilitation.Auth
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.rehabilitation.R
import com.example.rehabilitation.User.fragmentUser.HomeFragment
import com.example.rehabilitation.databinding.ActivityAuthDoctorBinding
class AuthDoctorActivity : AppCompatActivity() {
lateinit var binding: ActivityAuthDoctorBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAuthDoctorBinding.inflate(layoutInflater)
setContentView(binding.root)
//Вывод фрагмента на активити при первоначальной загрузке
supportFragmentManager.beginTransaction()
.replace(R.id.CLAutDoctor, AuthDoctorFragment.newInstance())
.commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
}
override fun onDestroy() {
super.onDestroy()
finish()
}
}

View File

@ -0,0 +1,157 @@
package com.example.rehabilitation.Auth
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomDangerToast
import com.example.admin.Toast.showCustomInfoToast
import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.UserDoctorToken
import com.example.rehabilitation.databinding.ActivityAuthDoctorBinding
import com.example.rehabilitation.databinding.FragmentAuthDoctorBinding
import com.example.rehabilitation.model_adapter.Doctor.DoctorModel
import com.example.rehabilitation.prefUserDoctorToken
import com.example.sqlitework.dip.MainViewModel
class AuthDoctorFragment : Fragment() {
lateinit var binding: FragmentAuthDoctorBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAuthDoctorBinding.inflate(layoutInflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
data_prefDoctorPatientToken()
liveDoctorAuthCurrent()
//Авторизация врача
//Нажатие на кнопку авторизации
binding.buttonAuthorizationDoctor.setOnClickListener{
var email = binding.editTextEmailDoctor.text.toString()
var password = binding.editTextPasswordDoctor.text.toString()
if(email !="" || password !=""){
AuthorizationDoctor(email,password)
Log.d("Result","email email - $email")
Log.d("Result","password password - $password")
}
else{
Toast(requireContext()).showCustomInfoToast("Не все поля заполнены", requireActivity())
}
}
//Переход от авторизации врача к пациенту
binding.btnAutPatient.setOnClickListener{
val intent = Intent(requireContext(), AuthorizationActivity::class.java)
activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана
startActivity(intent)
}
}
private fun liveDoctorAuthCurrent() = with(binding) {
model.liveAuthDoctorCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
if(it.id == "0"){
Toast(requireContext()).showCustomDangerToast("Такого аккаунта нету", requireActivity())
}
else{
saveUserDoctorToken(it.login)
if(UserDoctorToken !=""){
val intent = Intent(requireContext(), UserSettingActivity::class.java)
activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана
startActivity(intent)
}
}
}
}
//Фиксируем токен врача
private fun data_prefDoctorPatientToken() {
prefUserDoctorToken = activity?.getSharedPreferences("UserDoctorToken", Context.MODE_PRIVATE)
UserDoctorToken = prefUserDoctorToken?.getString("userdoctortoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
}
//Записываем число
fun saveUserDoctorToken(userdoctortoken: String) {
val editer = prefUserDoctorToken?.edit()
editer?.putString("userdoctortoken", userdoctortoken)
editer?.apply()
UserDoctorToken = userdoctortoken
}
//Функция очистки данных
fun clearUserDoctorToken() {
val edit = prefUserDoctorToken?.edit()
edit?.clear()
edit?.apply()
UserDoctorToken = ""
}
private fun AuthorizationDoctor(login:String,password:String){
val db = MainDB.getDB(requireContext())
db.getDaoDoctor().getAuthItemDoctor(login,password).asLiveData().observe(requireActivity()) {itPatient->
if (itPatient.isNullOrEmpty()) {
val item = DoctorModel(
"0",
"",
"",
"",
// it.email,
login,
""
)
model.liveAuthDoctorCurrent.value = item
}
else{
val item = DoctorModel(
itPatient[0].id.toString(),
"",
"",
"",
// it.email,
login,
""
)
model.liveAuthDoctorCurrent.value = item
}
}
}
override fun onDestroy() {
super.onDestroy()
activity?.finish()
}
companion object {
fun newInstance() = AuthDoctorFragment()
}
}

View File

@ -0,0 +1,198 @@
package com.example.rehabilitation.Auth
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import com.example.admin.Toast.showCustomDangerToast
import com.example.admin.Toast.showCustomInfoToast
import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.counter1
import com.example.rehabilitation.counter2
import com.example.rehabilitation.databinding.FragmentAuthBinding
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.UserDoctorToken
import com.example.rehabilitation.UserPatientToken
import com.example.rehabilitation.model_adapter.Doctor.DoctorModel
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.pref
import com.example.rehabilitation.prefDoctor
import com.example.rehabilitation.prefUserDoctorToken
import com.example.rehabilitation.prefUserPatientToken
import com.example.rehabilitation.tokenClass
import com.example.rehabilitation.tokenClassDoctor
import com.example.sqlitework.dip.MainViewModel
class AuthFragment : Fragment() {
private lateinit var binding: FragmentAuthBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentAuthBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
data_prefUserPatientToken()
livePatientAuthCurrent()
//Авиризация пациента
binding.buttonAuthorizationPatient.setOnClickListener {
var email = binding.editTextEmailPatient.text.toString()
var password = binding.editTextPasswordPatient.text.toString()
if (email != "" || password != "") {
AuthorizationPatient(email, password)
Log.d("Result", "email email - $email")
Log.d("Result", "password password - $password")
} else {
Toast(requireContext()).showCustomInfoToast(
"Не все поля заполнены",
requireActivity()
)
}
}
//Если пользователь решил зайти в аккаунт врача и не подумал о том что не сможет вернуться со страницы авторизации, то он может нажать данную кнопку, и в случае если он был авторизован, то его вернет в приложение
binding.btnBack.setOnClickListener {
if (UserPatientToken != "") {
val intent = Intent(requireContext(), MainActivity::class.java)
startActivity(intent)
activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана
} else {
Toast(requireContext()).showCustomInfoToast("Авторизуйтесь", requireActivity())
}
}
//Переход вход для врача
binding.txtDoctor.setOnClickListener {
val intent = Intent(requireContext(), AuthDoctorActivity::class.java)
startActivity(intent)
activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана
}
}
//Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране
fun data_prefUserPatientToken() {
prefUserPatientToken =
activity?.getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE)
UserPatientToken = prefUserPatientToken?.getString(
"userpatienttoken",
""
)!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
}
//Записываем число
fun saveUserPatientToken(userpatienttoken: String) {
val editer = prefUserPatientToken?.edit()
editer?.putString("userpatienttoken", userpatienttoken)
editer?.apply()
UserPatientToken = userpatienttoken
}
//Функция очистки данных
fun clearUserPatientToken() {
val edit = prefUserPatientToken?.edit()
edit?.clear()
edit?.apply()
UserPatientToken = ""
}
private fun AuthorizationPatient(login: String, password: String) {
val db = MainDB.getDB(requireContext())
Log.d("Ressadsdasdasda3", "sadsdasdasda")
db.getDaoPatient().getAuthItemPatient(login, password).asLiveData()
.observe(requireActivity()) { itPatient ->
if (itPatient.isNullOrEmpty()) {
val item = PatientModel(
"0",
"",
"",
"",
"",
"",
//it.email,
login,
"",
)
model.liveAuthPatientCurrent.value = item
} else {
val item = PatientModel(
itPatient[0].id.toString(),
"",
"",
"",
"",
"",
//it.email,
login,
"",
)
model.liveAuthPatientCurrent.value = item
}
}
}
private fun livePatientAuthCurrent() = with(binding) {
model.liveAuthPatientCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
Log.i("12312", "sadas")
if (it.id == "0") {
Log.i("4444", "4444")
Toast(requireContext()).showCustomDangerToast(
"Такого аккаунта нету",
requireActivity()
)
} else {
Log.i("5555", "5555")
UserPatientToken = it.login
saveUserPatientToken(it.login)
if (UserPatientToken != "") {
val intent = Intent(requireContext(), MainActivity::class.java)
activity?.finish()//Закрываем старый экран, для того чтобы очитсить оперативную память от лишнего хранения экрана
startActivity(intent)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
activity?.finish()
}
companion object {
fun newInstance() = AuthFragment()
}
}

View File

@ -0,0 +1,32 @@
package com.example.rehabilitation.Auth
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.ActivityAuthorizationBinding
class AuthorizationActivity : AppCompatActivity() {
private lateinit var binding: ActivityAuthorizationBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityAuthorizationBinding.inflate(layoutInflater)
setContentView(binding.root)
supportFragmentManager.beginTransaction().replace(R.id.constraintLayoutAuth, AuthFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
}
override fun onDestroy() {
super.onDestroy()
finish()
}
}

View File

@ -0,0 +1,5 @@
package com.example.rehabilitation.Calendare
class MonthCalendarViewHolder {
}

View File

@ -0,0 +1,137 @@
package com.example.rehabilitation
import android.content.SharedPreferences
import com.example.rehabilitation.model_adapter.Month.MonthModel
import com.example.rehabilitation.model_adapter.Progress.AfterListModel
import com.example.rehabilitation.model_adapter.Progress.BeforeListModel
import com.example.rehabilitation.model_adapter.Progress.ProgressModel
import java.io.File
import java.io.FileOutputStream
//Постоянное хранилище
var prefUserPatientToken: SharedPreferences? = null
var UserPatientToken:String = ""
var prefUserDoctorToken: SharedPreferences? = null
var UserDoctorToken:String = ""
var prefPatientDoctorNew: SharedPreferences? = null
var PatientDoctorNew:Int = 0
var pref: SharedPreferences? = null
var prefDoctor: SharedPreferences? = null
var prefSportCursNumber: SharedPreferences? = null
var prefCursDay: SharedPreferences? = null
var SportCursDay :Int = 0
//7 дней пройдено
var prefSport7Day: SharedPreferences? = null
var Sport7Day :Int = 0
//15 дней пройдено
var prefSport15Day: SharedPreferences? = null
var Sport15Day :Int = 0
//15 дней пройдено и отправлен отчет
var prefSport15DayAll: SharedPreferences? = null
var Sport15DayAll :Int = 0
var prefSportCursDayNumber: SharedPreferences? = null
var SportCursDayNumber :Int = 0
var prefSport: SharedPreferences? = null
var SportUserTrue = 0
var prefCursDangerDayBefore: SharedPreferences? = null
var SportCursDayDangerBefore:Int = 0
var prefCursDangerDayAfter: SharedPreferences? = null
var SportCursDayDangerAfter:Int = 0
var prefCursDayNull: SharedPreferences? = null
var CursDayNull:String = ""
var prefSportPlusCount: SharedPreferences? = null
var SportPlusCount:Int = 0
var prefSportMaxCount: SharedPreferences? = null
var SportMaxCount:Int = 0
var prefDayBefore: SharedPreferences? = null
var DayBefore:String = ""
var prefDayAfter: SharedPreferences? = null
var DayAfter:String = ""
var prefPauseDay: SharedPreferences? = null
var PauseDay:String = ""
var prefBlock: SharedPreferences? = null
var Block:String = ""
var prefFIO: SharedPreferences? = null
var FIO:String = ""
var prefEmailPatient: SharedPreferences? = null
var EmailPatient:String = ""
//Дата начала тренировки
var prefSportDateStart: SharedPreferences? = null
var SportDateStart:String = ""
var prefUser: SharedPreferences? = null
//Хранилище для анкеты
//var questionnaire: SharedPreferences? = null
var questionnaire_before :String = ""
var questionnaire_after:String = ""
var nameSport :String = ""
var countSport:Int? = null
var countSportPlus:String = ""
//Ключи для хранилишь
//Для пациента
var tokenClass:String = ""
var counter1:String = ""
//Для врача
var counter2:String = ""
var tokenClassDoctor:String = ""
var countCategory:String = ""
//Отчет по ребилитации
var listCheckSportDay:String = ""
//Доктор
var loginDoctor:String = "maxi05092003"
//Пациент
var loginPatient:String = "t.t.maxi05092003@gmail.com"
//Хранения отчета на время
var checkDaySportString:String = ""
//Хранения для перехода на страницу
var daySpoartOpen:Int = 0
var daySpoartOpenDate:String = ""
val daySpoartOpenKey:Int = 12321313
//var itemDayOpenDate:MonthModel
//Анкетирование
var listBefore:List<BeforeListModel> = listOf()
var listAfter:List<AfterListModel> = listOf()
//Прогрес
var listProgressAll:List<ProgressModel> = listOf()
var listProgressCheck:List<ProgressModel> = listOf()
var uriFileEF: File? =null
var fileUri2: FileOutputStream? =null
//Переменная для хранения дня, чтобы при нажатие на главной тсранице или в календаре
var dateHomeCalendare:String = ""
class Hranilihe {
}

View File

@ -0,0 +1,31 @@
package com.example.rehabilitation
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import com.example.rehabilitation.User.fragmentUser.InformationFragment
import com.example.rehabilitation.User.fragmentUser.SceduleFragment
import com.example.rehabilitation.databinding.ActivityInformationBinding
class InformationActivity : AppCompatActivity() {
var backPressedTime: Long = 0
private lateinit var binding: ActivityInformationBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityInformationBinding.inflate(layoutInflater)
setContentView(binding.root)
supportFragmentManager.beginTransaction()
.replace(R.id.CLInformation, InformationFragment.newInstance())
.commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
}
override fun onBackPressed() {
val intetn = Intent(this, MainActivity::class.java)
startActivity(intetn)
finish()
}
}

View File

@ -1,18 +1,45 @@
package com.example.rehabilitation package com.example.rehabilitation
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent import android.content.Intent
import android.icu.text.SimpleDateFormat
import android.icu.util.Calendar
import android.os.Bundle import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.view.GravityCompat
import androidx.lifecycle.LifecycleOwner
import com.example.rehabilitation.Auth.AuthDoctorActivity
import com.example.rehabilitation.Auth.AuthorizationActivity
import com.example.rehabilitation.User.fragmentUser.CalendarFragment import com.example.rehabilitation.User.fragmentUser.CalendarFragment
import com.example.rehabilitation.User.fragmentUser.HomeFragment import com.example.rehabilitation.User.fragmentUser.HomeFragment
import com.example.rehabilitation.User.fragmentUser.InformationFragment import com.example.rehabilitation.User.fragmentUser.InformationFragment
import com.example.rehabilitation.User.fragmentUser.ProgresFragment import com.example.rehabilitation.User.fragmentUser.ProgresFragment
import com.example.rehabilitation.User.fragmentUser.SceduleFragment import com.example.rehabilitation.User.fragmentUser.SceduleFragment
import com.example.rehabilitation.databinding.ActivityMainBinding import com.example.rehabilitation.databinding.ActivityMainBinding
import com.example.rehabilitation.model_adapter.DataModel
import com.google.firebase.database.ktx.database
import com.google.firebase.ktx.Firebase
import java.time.LocalDate
import java.util.Date
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
var backPressedTime: Long = 0
private lateinit var binding: ActivityMainBinding private lateinit var binding: ActivityMainBinding
//Для постоянного охаранения данных(для токена)
//var pref: SharedPreferences? = null
private val dataModel: DataModel by viewModels()//Для передачи данных
var sdf: SimpleDateFormat = SimpleDateFormat("EEEE")
var d: Date = Date()
var dayOfTheWeek: String = sdf.format(d)
@SuppressLint("DiscouragedApi") @SuppressLint("DiscouragedApi")
@ -21,6 +48,15 @@ class MainActivity : AppCompatActivity() {
binding = ActivityMainBinding.inflate(layoutInflater) binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
//Функция инициализации хранилиша для токена
data_prefUserPatientToken()
dataModel.fragmentMenu.observe(this as LifecycleOwner, {
binding.buttonNavigation.selectedItemId = it
})
//Функция инициализации фрагметов //Функция инициализации фрагметов
fragment_inicializ() fragment_inicializ()
@ -32,17 +68,171 @@ class MainActivity : AppCompatActivity() {
binding.btnSetting.setOnClickListener { binding.btnSetting.setOnClickListener {
val intent = Intent(this, SettingActivity::class.java) val intent = Intent(this, SettingActivity::class.java)
startActivity(intent) startActivity(intent)
finish()
}
binding.btnInformation.setOnClickListener {
val intent = Intent(this, InformationActivity::class.java)
startActivity(intent)
finish()
} }
val database = Firebase.database
val myRef = database.getReference("message1235322")
myRef.setValue("Hello, World!")
//binding.imageView3.resources.getIdentifier("b3_1","drawable",this.packageName); //binding.imageView3.resources.getIdentifier("b3_1","drawable",this.packageName);
//Выводим сегоднящнюю дату
addDate()
}
override fun onBackPressed() {
if (backPressedTime + 3000 > System.currentTimeMillis()) {
super.onBackPressed()
finish()
} else {
AlertDialog.Builder(this@MainActivity)
.setTitle("Выйти")
.setMessage("Вы точно хотите выйти из приложения?")
.setPositiveButton("Да") { dialog, whichButton ->
super.onBackPressed()
}
.setNegativeButton("Нет") { dialog, whichButton ->
}
.show()
}
backPressedTime = System.currentTimeMillis()
}
private fun addDate() {
val calendar: Calendar = Calendar.getInstance()
val sdf: SimpleDateFormat = SimpleDateFormat("EEEE")
val d: Date = Date()
val DayOfTheWeek: String = sdf.format(d)
val Day = calendar.get(Calendar.DATE)
val Month = calendar.get(Calendar.MONTH).plus(1)
var day = Day.toString()
var month = ""
var date_of_the_week = ""
when (Month) {
1 -> month="Январь"
2 -> month="Февраль"
3 -> month="Март"
4 -> month="Апрель"
5 -> month="Май"
6 -> month="Июнь"
7 -> month="Июль"
8 -> month="Август"
9 -> month="Сентябрь"
10 -> month="Октябрь"
11 -> month="Ноябрь"
12 -> month="Декабрь"
else -> { // обратите внимание на блок
month=""
}
}
when (dayOfTheWeek) {
"Monday" -> date_of_the_week="Пн"
"Tuesday" -> date_of_the_week="Вт"
"Wednesday" -> date_of_the_week="Ср"
"Thursday" -> date_of_the_week="Чт"
"Friday" -> date_of_the_week="Пт"
"Saturday" -> date_of_the_week="Сб"
"Sunday" -> date_of_the_week="Вс"
"Понедельник" -> date_of_the_week="Пн"
"Вторник" -> date_of_the_week="Вт"
"Стреда" -> date_of_the_week="Ср"
"Четверг" -> date_of_the_week="Чт"
"Пятница" -> date_of_the_week="Пт"
"Суббота" -> date_of_the_week="Сб"
"Воскресенье" -> date_of_the_week="Вс"
else -> {
date_of_the_week=""
}
} }
System.out.println(calendar.get(Calendar.DATE))
//binding.txtDate.setText("${day}" +" "+ "${month}" +" "+ "(${date_of_the_week})")
binding.txtDate.setText("${day}" +" "+ "${month}")
}
// interface IOnBackPressed {
// fun onBackPressed(): Boolean
// }
//
// override fun onBackPressed() {
// val fragment =
// this.supportFragmentManager.findFragmentById(R.id.placeHolderFragment)
// (fragment as? IOnBackPressed)?.onBackPressed()?.not()?.let {
// super.onBackPressed()
// }
// }
// override fun onBackPressed() {
// AlertDialog.Builder(this).apply {
// setTitle("Подтверждение")
// setMessage("Вы уверены, что хотите выйти из программы?")
//
// setPositiveButton("Таки да") { _, _ ->
// super.onBackPressed()
// }
//
// setNegativeButton("Нет"){_, _ ->
// // if user press no, then return the activity
// Toast.makeText(this@MainActivity, "Thank you",
// Toast.LENGTH_LONG).show()
// }
// setCancelable(true)
// }.create().show()
// }
//Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране
fun data_prefUserPatientToken() {
prefUserPatientToken = getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE)
UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
prefPatientDoctorNew = getSharedPreferences("PatientDoctorNew", Context.MODE_PRIVATE)
PatientDoctorNew = prefPatientDoctorNew?.getInt("patientdoctornew", 0)!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
if (UserPatientToken == ""){
if(PatientDoctorNew == 1){
val intetn = Intent(this, AuthorizationActivity::class.java)
startActivity(intetn)
}
else{
val intetn = Intent(this, AuthDoctorActivity::class.java)
startActivity(intetn)
}
}
else{
//Toast.makeText(this, "Добро пожаловать", Toast.LENGTH_SHORT).show()
}
}
//Записываем число
fun saveUserPatientToken(userpatienttoken: String) {
val editer = prefUserPatientToken?.edit()
editer?.putString("userpatienttoken", userpatienttoken)
editer?.apply()
UserPatientToken = userpatienttoken
}
override fun onDestroy() { override fun onDestroy() {
super.onDestroy() super.onDestroy()
finish()
} }
override fun onResume() { override fun onResume() {
@ -54,12 +244,12 @@ class MainActivity : AppCompatActivity() {
fun fragment_inicializ() { fun fragment_inicializ() {
//Вывод фрагмента на активити при первоначальной загрузке //Вывод фрагмента на активити при первоначальной загрузке
supportFragmentManager.beginTransaction() supportFragmentManager.beginTransaction()
.replace(R.id.placeHolderFragment, HomeFragment.newInstance()) .replace(R.id.placeHolderFragment, SceduleFragment.newInstance())
.commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем .commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
//Эран который будет выбран по умолчанию(кнопка которая будет прожата по умолчанию) //Эран который будет выбран по умолчанию(кнопка которая будет прожата по умолчанию)
binding.buttonNavigation.selectedItemId = R.id.home//По умолчанию и так первая, но на всякий случай выберу еще програмным путем первую ячейку binding.buttonNavigation.selectedItemId = R.id.schedule//По умолчанию и так первая, но на всякий случай выберу еще програмным путем первую ячейку
//Нажатие на bottom navigation //Нажатие на bottom navigation
binding.buttonNavigation.setOnItemSelectedListener { binding.buttonNavigation.setOnItemSelectedListener {
@ -71,17 +261,19 @@ class MainActivity : AppCompatActivity() {
R.id.calendar -> { R.id.calendar -> {
supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, CalendarFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, CalendarFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
} }
R.id.home -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту // R.id.home -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту
supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, HomeFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем // supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, HomeFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
} // }
R.id.progress -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту R.id.progress -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту
supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, ProgresFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, ProgresFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
} }
R.id.information -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту // R.id.information -> {//Если вы не авторизованный пользваотель то вам не будет доступен доступ к данном фрагменту
supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, InformationFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем // supportFragmentManager.beginTransaction().replace(R.id.placeHolderFragment, InformationFragment.newInstance()).commit()//Заменяем наш экран на фрагмент (используем наш экран как основу)//R.id.placeHolder - куда всталяем //MainFragment.newInstance() - это то что мы вставляем
} // }
} }
true true
} }
} }
} }

View File

@ -1,9 +1,7 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@ -16,7 +14,7 @@ interface Dao {
//Список по дням //Список по дням
@Query("SELECT * FROM items ORDER BY day ASC") @Query("SELECT * FROM items ORDER BY id ASC")
fun getAllItems(): Flow<List<Item>> fun getAllItems(): Flow<List<Item>>
//Список определенного дня //Список определенного дня
@ -27,6 +25,9 @@ interface Dao {
@Query("UPDATE items SET `check` = 1 WHERE id = :id") @Query("UPDATE items SET `check` = 1 WHERE id = :id")
fun updateItems(id : String) fun updateItems(id : String)
@Query("UPDATE items SET `day` = :day WHERE date = :date")
fun updateDay(day:String,date : String)
//Очистка таблицы //Очистка таблицы
@Query("DELETE FROM items") @Query("DELETE FROM items")
fun deleteItem() fun deleteItem()

View File

@ -0,0 +1,60 @@
package com.example.rehabilitation.Room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoDaySport {
//Таблица определенного дня
@Insert
fun insertItemDaySport(itemDaySport:ItemDaySport)
//Список определенного дня
@Query("SELECT * FROM DaySport ORDER BY day ASC")
fun getAllItemDaySportDay(): Flow<List<ItemDaySport>>
//Список определенного дня
@Query("SELECT * FROM DaySport WHERE day = :day AND visible = 1")
fun getAllItemDaySport(day:String): Flow<List<ItemDaySport>>
//Список определенного дня
@Query("SELECT id,day,category, `check`,COUNT(*) as visible FROM DaySport WHERE visible='1' GROUP BY day ORDER BY day ASC")
fun getAllProgres(): Flow<List<ItemDaySport>>
//Список определенного дня
@Query("SELECT id,day,category, COUNT(*) as `check`, visible FROM DaySport WHERE `check`='1' and visible='1' GROUP BY day ORDER BY day ASC")
fun getcheckProgress(): Flow<List<ItemDaySport>>
//Получаем любую рандомну строку для того чтобы использовать его дату в редактирование списка
@Query("SELECT * FROM DaySport ORDER BY day DESC LIMIT 1")
fun getItemDaySportRandomOne(): Flow<List<ItemDaySport>>
@Update
fun updateCheckDaySport(itemDaySport: ItemDaySport)
@Query("SELECT DaySport.id as id ,DaySport.day as day,DaySport.category as category, DaySport.`check` as `check`,DaySport.visible as visible, SportCategory.`desc` as `desc`, SportCategory.image as categoryImage FROM DaySport JOIN SportCategory ON DaySport.category = SportCategory.category WHERE DaySport.day == :date ORDER BY day ASC")
fun getListJoinDaySportAndSportCategory(date:String): Flow<List<ItemDaySportAndSportCategory>>
//Обновляем видимость у записей с данным
@Query("UPDATE DaySport SET visible = 1 WHERE category = :category AND day>=:date")
fun updateVisibleDaySportTrue(category:String,date :String)
@Query("UPDATE DaySport SET visible = 0 WHERE category = :category AND day>=:date")
fun updateVisibleDaySportFalse(category:String,date :String)
//Обновление что выполнил упражнение
@Query("UPDATE DaySport SET `check` = 1 WHERE id = :id")
fun updateCheckDaySport(id:Int)
@Query("UPDATE DaySport SET `check` = 2 WHERE id = :id")
fun updateNoCheckDaySport(id:Int)
//Очистка таблицы
@Query("DELETE FROM DaySport")
fun deleteItemDaySport()
}

View File

@ -1,4 +1,4 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Insert import androidx.room.Insert
@ -12,15 +12,15 @@ interface DaoImage {
fun insertItemImage(itemImage:ItemImage) fun insertItemImage(itemImage:ItemImage)
//Список определенного дня //Список определенного дня
@Query("SELECT * FROM itemImage ") @Query("SELECT * FROM Image")
fun getAllItemImage(): Flow<List<ItemImage>> fun getAllItemImage(): Flow<List<ItemImage>>
//Список определенного дня //Список определенного дня
@Query("SELECT * FROM itemImage WHERE article = :article ORDER BY id ASC") @Query("SELECT * FROM Image WHERE article = :article ORDER BY id ASC")
fun getAllItemImage(article:String): Flow<List<ItemImage>> fun getAllItemImage(article:String): Flow<List<ItemImage>>
//Очистка таблицы //Очистка таблицы
@Query("DELETE FROM itemImage") @Query("DELETE FROM Image")
fun deleteItemImage() fun deleteItemImage()
} }

View File

@ -0,0 +1,53 @@
package com.example.rehabilitation.Room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoSportCategory {
//Таблица по по дням
@Insert
fun insertItemSportCategory(item:ItemSportCategory)
//Таблица определенного дня
//Список по дням
@Query("SELECT * FROM SportCategory WHERE category = :category")
fun getAllItemsSportCategory(category:String): Flow<List<ItemSportCategory>>
// @Query("SELECT * FROM SportCategory WHERE image = :category")
// fun getAllItemsSportCategoryEdit(category:String): Flow<List<ItemSportCategory>>
//
@Query("SELECT id, name, `desc`, count,COUNT(*) as image,category,article,`check` FROM SportCategory WHERE image = :category and `check`=0")
fun getAllItemsSportCategoryCount(category:String): Flow<List<ItemSportCategory>>
@Query("SELECT id, name, `desc`,COUNT(*) as count,image,category,article,`check` FROM SportCategory WHERE image = :category and `check`=0")
fun getAllItemsSportCategoryCountSport(category:String): Flow<List<ItemSportCategory>>
//По артикулу
@Query("SELECT id, name, `desc`,COUNT(*) as count,image,category,article,`check` FROM SportCategory WHERE article = :article")
fun getSportArticle(article:String): Flow<List<ItemSportCategory>>
//Rjkbxtcndj eghf;ytybq
@Query("SELECT id, COUNT(*) as name, `desc`, count, image,category,article,`check` FROM SportCategory WHERE article = :article and `check` = 0")
fun getCountSportCategory(article:String): Flow<List<ItemSportCategory>>
//Список определенного дня
// @Query("SELECT * FROM itemDay")
// fun getAllItemDay(): Flow<List<ItemDay>>
//Обновление по переднному параметру
// @Query("UPDATE itemSportCategory SET `check` = 1 WHERE id = :id")
// fun updateItemsSportCategory(id : String)
//Очистка таблицы
// @Query("DELETE FROM SportCategory")
// fun deleteItemSportCategory()
}

View File

@ -1,23 +1,21 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.Dao import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query import androidx.room.Query
import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.Flow
@Dao @Dao
interface DaoSportCategory { interface DaoSportPatient {
//Таблица по по дням //Таблица по по дням
@Insert @Insert
fun insertItemSportCategory(item:ItemSportCategory) fun insertItemSportPatient(item:ItemSportPatient)
//Таблица определенного дня //Таблица определенного дня
//Список по дням //Список по дням
@Query("SELECT * FROM itemSportCategory WHERE image = :category") @Query("SELECT * FROM SportPatient WHERE image = :category")
fun getAllItemsSportCategory(category:String): Flow<List<ItemSportCategory>> fun getAllItemsSportPatient(category:String): Flow<List<ItemSportPatient>>
//Список определенного дня //Список определенного дня
// @Query("SELECT * FROM itemDay") // @Query("SELECT * FROM itemDay")
@ -28,7 +26,7 @@ interface DaoSportCategory {
// fun updateItemsSportCategory(id : String) // fun updateItemsSportCategory(id : String)
//Очистка таблицы //Очистка таблицы
@Query("DELETE FROM itemSportCategory") // @Query("DELETE FROM SportPatient")
fun deleteItemSportCategory() // fun deleteItemSportPatient()
} }

View File

@ -1,11 +1,10 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import java.util.Date
@Entity(tableName = "items") @Entity(tableName = "Items")
data class Item( data class Item(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
var id:Int? = null, var id:Int? = null,

View File

@ -1,10 +1,10 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
@Entity(tableName = "itemDaySport") @Entity(tableName = "DaySport")
data class ItemDaySport( data class ItemDaySport(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
var id:Int? = null, var id:Int? = null,
@ -14,5 +14,7 @@ data class ItemDaySport(
var category:String, var category:String,
@ColumnInfo(name = "check") @ColumnInfo(name = "check")
var check:Int, var check:Int,
@ColumnInfo(name = "visible")
var visible:Int,
) )

View File

@ -0,0 +1,24 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "ItemDaySportAndSportCategory")
data class ItemDaySportAndSportCategory(
@ColumnInfo(name = "id")
var id:Int,
@ColumnInfo(name = "day")
var day:String,
@ColumnInfo(name = "category")
var category:String,
@ColumnInfo(name = "check")
var check:Int,
@ColumnInfo(name = "visible")
var visible:Int,
@ColumnInfo(name = "desc")
var desc:String,
@ColumnInfo(name = "categoryImage")
var categoryImage:String,
)

View File

@ -1,10 +1,10 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
@Entity(tableName = "itemImage") @Entity(tableName = "Image")
data class ItemImage( data class ItemImage(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
var id:Int? = null, var id:Int? = null,

View File

@ -0,0 +1,16 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "ItemProgressAll")
data class ItemProgressAll(
@ColumnInfo(name = "date")
var date:String,
@ColumnInfo(name = "countAll")
var countAll:Int,
@ColumnInfo(name = "category")
var category:String,
)

View File

@ -0,0 +1,16 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "ItemProgressCheck")
data class ItemProgressCheck(
@ColumnInfo(name = "date")
var date:String,
@ColumnInfo(name = "countCheck")
var countCheck:Int,
@ColumnInfo(name = "category")
var category:String,
)

View File

@ -0,0 +1,20 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "ItemProgressDay")
data class ItemProgressDay(
@PrimaryKey(autoGenerate = true)
var id:Int? = null,
@ColumnInfo(name = "countAll")
var countAll:Int,
@ColumnInfo(name = "CountCheckTrue")
var CountCheckTrue:Int,
@ColumnInfo(name = "category")
var category:String,
@ColumnInfo(name = "date")
var date:Int,
)

View File

@ -0,0 +1,26 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "SportCategory")
data class ItemSportCategory(
@PrimaryKey(autoGenerate = true)
var id: Int? = null,
@ColumnInfo(name = "name")
var name: String,
@ColumnInfo(name = "desc")
var desc: String,
@ColumnInfo(name = "count")
var count: String,
@ColumnInfo(name = "image")
var image: String,
@ColumnInfo(name = "category")
var category: String,
@ColumnInfo(name = "article")
var article: String,
@ColumnInfo(name = "check")
var check: Int
)

View File

@ -0,0 +1,9 @@
package com.example.rehabilitation.Room
import androidx.room.ColumnInfo
data class ItemSportCategoryCount(
@ColumnInfo(name = "count")
var count:String,
)

View File

@ -1,12 +1,11 @@
package com.example.rehabilitation.db package com.example.rehabilitation.Room
import androidx.room.ColumnInfo import androidx.room.ColumnInfo
import androidx.room.Entity import androidx.room.Entity
import androidx.room.PrimaryKey import androidx.room.PrimaryKey
import java.util.Date
@Entity(tableName = "itemSportCategory") @Entity(tableName = "SportPatient")
data class ItemSportCategory( data class ItemSportPatient(
@PrimaryKey(autoGenerate = true) @PrimaryKey(autoGenerate = true)
var id:Int? = null, var id:Int? = null,
@ColumnInfo(name = "name") @ColumnInfo(name = "name")
@ -17,7 +16,7 @@ data class ItemSportCategory(
var count:String, var count:String,
@ColumnInfo(name = "image") @ColumnInfo(name = "image")
var image:String, var image:String,
@ColumnInfo(name = "category") @ColumnInfo(name = "day")
var category:String var day:String
) )

View File

@ -0,0 +1,162 @@
package com.example.rehabilitation.Room
import android.content.Context
import androidx.room.Database
import androidx.room.Room.databaseBuilder
import androidx.room.RoomDatabase
import com.example.rehabilitation.Room.Questionnaire.After.DaoAfterQuestionnaire
import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire
import com.example.rehabilitation.Room.Questionnaire.Before.DaoBeforeQuestionnaire
import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire
import com.example.rehabilitation.Room.dbUser.dbDoctor.DaoDoctor
import com.example.rehabilitation.Room.dbUser.dbDoctor.ItemDoctor
import com.example.rehabilitation.Room.dbUser.dbPatient.DaoPatient
import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient
@Database(entities = [
Item::class,
ItemDaySport::class,
ItemImage::class,
ItemSportCategory::class,
ItemSportPatient::class,
ItemDoctor::class,
ItemPatient::class,
ItemBeforeQuestionnaire::class,
ItemAfterQuestionnaire::class,
], version = 12)
abstract class MainDB: RoomDatabase() {
abstract fun getDao(): Dao
abstract fun getDaoDaySport(): DaoDaySport
abstract fun getDaoImage(): DaoImage
abstract fun getDaoSportCategory(): DaoSportCategory
abstract fun getDaoSportPatient(): DaoSportPatient
abstract fun getDaoDoctor(): DaoDoctor
abstract fun getDaoPatient(): DaoPatient
abstract fun getDaoQB(): DaoBeforeQuestionnaire
abstract fun getDaoQA(): DaoAfterQuestionnaire
//
companion object{
// fun getDB(context: Context):MainDB{
// return Room.databaseBuilder(
// context.applicationContext,
// MainDB::class.java,
// "ClogonV22.db"
// ).build()
//
// }
//private val DB_NAME: String? = "ReabilitationV2.db"
//
// fun buildDatabase(context: Context): MainDB? {
// val dbFile = context.getDatabasePath(DB_NAME)
// if (!dbFile.exists()) {
// copyDatabaseFile(dbFile.absolutePath)
// }
// return databaseBuilder(
// context.applicationContext,
// MainDB::class.java, DB_NAME
// )
// .build()
// }
//
// private fun copyDatabaseFile(destinationPath: String) {
// // code to copy the file from assets/database directory to destinationPath
// }
fun getDB(context: Context):MainDB{
return databaseBuilder(context, MainDB::class.java,"ReabilitationV4.db")
.createFromAsset("ReabilitationV4.db")
.fallbackToDestructiveMigration()
.build()
}
}
}
/*abstract class MainDB: RoomDatabase(){
abstract fun getDao(): Dao
abstract fun getDaoDaySport(): DaoDaySport
abstract fun getDaoImage(): DaoImage
abstract fun getDaoSportCategory(): DaoSportCategory
abstract fun getDaoSportPatient(): DaoSportPatient
override fun init(configuration: DatabaseConfiguration) {
importExistingDatabase(
configuration.context,
true
) //<<<<<<<<<< Invokes the Import of the Exisiting Database.
super.init(configuration)
}
private fun importExistingDatabase(context: Context, throw_exception: Boolean) {
val buffer_size = 32768
val dbpath = context.getDatabasePath(DBNAME)
if (dbpath.exists()) {
return // Database already exists
}
// Just in case make the directories
val dirs = File(dbpath.parent)
dirs.mkdirs()
var stage = 0
val buffer = ByteArray(buffer_size)
var total_bytes_read: Long = 0
var total_bytes_written: Long = 0
var bytes_read = 0
try {
val assetdb = context.assets.open(DBNAME)
stage++
dbpath.createNewFile()
stage++
val realdb: OutputStream = FileOutputStream(dbpath)
stage++
while (assetdb.read(buffer).also { bytes_read = it } > 0) {
total_bytes_read = total_bytes_read + bytes_read
realdb.write(buffer, 0, bytes_read)
total_bytes_written = total_bytes_written + bytes_read
}
stage++
realdb.flush()
stage++
assetdb.close()
stage++
realdb.close()
stage++
} catch (e: IOException) {
var failed_at = ""
when (stage) {
0 -> failed_at = "Opening Asset " + DBNAME
1 -> failed_at = "Creating Output Database " + dbpath.absolutePath
2 -> failed_at = "Genreating Database OutputStream " + dbpath.absolutePath
3 -> failed_at = "Copying Data from Asset Database to Output Database. " +
" Bytes read=" + total_bytes_read.toString() +
" Bytes written=" + total_bytes_written.toString()
4 -> failed_at = "Flushing Written Data ($total_bytes_written bytes written)"
5 -> failed_at = "Closing Asset Database File."
6 -> failed_at = "Closing Created Database File."
}
val msg =
"""An error was encountered copying the Database from the asset file to New Database. The error was encountered whilst :-
$failed_at"""
Log.e("IMPORTDATABASE", msg)
e.printStackTrace()
if (throw_exception) {
throw RuntimeException(msg)
}
}
}
companion object {
const val DBNAME = "ClogonV3.db"
const val TB_MYTABLE = "mytable"
const val TB_MYOTHERTABLE = "myothertable"
const val TB_MYMAPPINGTABLE = "mymappingtable"
const val COL_MYTABLE_ID = BaseColumns._ID
const val COL_MYTABLE_NAME = "_name"
const val COL_MYTABLE_DESCRIPTION = "_description"
const val COL_MYOTHERTABLE_ID = BaseColumns._ID
const val COL_MYOTHERTABLE_OTHERDETAILS = "_otherdetails"
const val COL_MYMAPPINGTABLE_MYTABLEREFERENCE = "_mytable_reference"
const val COL_MYMAPPINGTABLE_MYOTEHERTABLEREFERENCE = "_myothertable_reference"
}
}*/

View File

@ -0,0 +1,44 @@
package com.example.rehabilitation.Room.Questionnaire.After
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.example.rehabilitation.Room.Item
import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoAfterQuestionnaire {
//Таблица по по дням
@Insert
fun insertAQ(itemAfterQuestionnaire: ItemAfterQuestionnaire)
//Таблица определенного дня
//// //Список по дням
// @Query("SELECT * FROM AfterQuestionnaire ORDER BY date ASC")
// fun getAllAQ(): Flow<List<ItemAfterQuestionnaire>>
//Весь список
@Query("SELECT * FROM AfterQuestionnaire ORDER BY date ASC")
fun getAllAQProgress(): Flow<List<ItemAfterQuestionnaire>>
//Список определенного дня
@Query("SELECT * FROM AfterQuestionnaire WHERE date = :date")
fun getAllAQDay(date:String): Flow<List<ItemAfterQuestionnaire>>
//Список определенного дня
@Query("SELECT * FROM AfterQuestionnaire WHERE date = :date")
fun getAllProgress(date:String): Flow<List<ItemAfterQuestionnaire>>
//Обновление по переднному параметру
//@Query("UPDATE AfterQuestionnaire SET `check` = 1 WHERE id = :id")
//fun updateAQ(id : String)
//Очистка таблицы
@Query("DELETE FROM AfterQuestionnaire")
fun deleteAQ()
}

View File

@ -0,0 +1,38 @@
package com.example.rehabilitation.Room.Questionnaire.After
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "AfterQuestionnaire")
data class ItemAfterQuestionnaire(
@PrimaryKey(autoGenerate = true)
var id:Int? = null,
@ColumnInfo(name = "one")
var one: String,
@ColumnInfo(name = "two")
var two: String,
@ColumnInfo(name = "three")
var three: String,
@ColumnInfo(name = "four")
var four:String,
@ColumnInfo(name = "five")
var five:String,
@ColumnInfo(name = "six")
var six:String,
@ColumnInfo(name = "seven")
var seven:String,
@ColumnInfo(name = "eight")
var eight:String,
@ColumnInfo(name = "nine")
var nine:String,
@ColumnInfo(name = "ten")
var ten:String,
@ColumnInfo(name = "eleven")
var elevenInt:String,
@ColumnInfo(name = "twelve")
var twelve:String,
@ColumnInfo(name = "date")
var date:String,
)

View File

@ -0,0 +1,38 @@
package com.example.rehabilitation.Room.Questionnaire.Before
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import com.example.rehabilitation.Room.Item
import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoBeforeQuestionnaire {
//Таблица по по дням
@Insert
fun insertBQ(item: ItemBeforeQuestionnaire)
//Таблица определенного дня
// // //Список по дням
// @Query("SELECT * FROM BeforeQuestionnaire ORDER BY date ASC")
// fun getAllBQ(): Flow<List<ItemAfterQuestionnaire>>
//Весь список
@Query("SELECT * FROM BeforeQuestionnaire ORDER BY date ASC")
fun getAllBQProgress(): Flow<List<ItemBeforeQuestionnaire>>
//Список определенного дня
@Query("SELECT * FROM BeforeQuestionnaire WHERE date = :date")
fun getAllBQDay(date:String): Flow<List<ItemBeforeQuestionnaire>>
//Обновление по переднному параметру
//@Query("UPDATE BeforeQuestionnaire SET `check` = 1 WHERE id = :id")
//fun updateBQ(id : String)
//Очистка таблицы
@Query("DELETE FROM BeforeQuestionnaire")
fun deleteBQ()
}

View File

@ -0,0 +1,33 @@
package com.example.rehabilitation.Room.Questionnaire.Before
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "BeforeQuestionnaire")
data class ItemBeforeQuestionnaire(
@PrimaryKey(autoGenerate = true)
var id:Int? = null,
@ColumnInfo(name = "one")
var one: String,
@ColumnInfo(name = "two")
var two: String,
@ColumnInfo(name = "three")
var three: String,
@ColumnInfo(name = "four")
var four:String,
@ColumnInfo(name = "five")
var five:String,
@ColumnInfo(name = "six")
var six:String,
@ColumnInfo(name = "seven")
var seven:String,
@ColumnInfo(name = "eight")
var eight:String,
@ColumnInfo(name = "nine")
var nine:String,
@ColumnInfo(name = "date")
var date:String,
)

View File

@ -0,0 +1,51 @@
package com.example.rehabilitation.Room.dbUser.dbDoctor
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.rehabilitation.Room.dbUser.dbPatient.ItemPatient
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoDoctor {
//Таблица определенного дня
@Insert
fun insertItemDoctor(itemDoctor:ItemDoctor)
//Список врачей
@Query("SELECT * FROM Doctor ORDER BY id ASC")
fun getAllItemDoctor(): Flow<List<ItemDoctor>>
//Список врачей
@Query("SELECT * FROM Doctor WHERE login")
fun getItemDoctor(): Flow<List<ItemDoctor>>
//Опредеоение авторизованного врача
@Query("SELECT * FROM Doctor WHERE login = :login AND password = :password")
fun getAuthItemDoctor(login:String, password:String): Flow<List<ItemDoctor>>
//Опредеоение авторизованного пациента
@Query("SELECT * FROM Doctor WHERE login = :login")
fun getAuthItemDoctorOutput(login:String): Flow<List<ItemDoctor>>
//Список определенного дня
// @Query("SELECT * FROM Doctor WHERE day = :day")
// fun getAllItemDaySport(day:String): Flow<List<ItemDoctor>>
//Обновление что выполнил упражнение
@Query("UPDATE Doctor SET name = :name, surname = :surname, patronymic= :patronymic,login=:login,password=:password WHERE login =:loginOld")
fun updateDoctor(loginOld:String, name:String,surname:String,patronymic:String,login:String,password: String)
//Обновление что выполнил упражнение
// @Query("UPDATE Doctor SET `check` = 1 WHERE id = :id")
// fun updateDoctor(id:Int)
//Очистка таблицы
// @Query("DELETE FROM Doctor")
// fun deleteItemDaySport()
}

View File

@ -0,0 +1,23 @@
package com.example.rehabilitation.Room.dbUser.dbDoctor
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Doctor")
data class ItemDoctor(
@PrimaryKey(autoGenerate = true)
var id:Int? = null,
@ColumnInfo(name = "name")//Имя
var name:String,
@ColumnInfo(name = "surname")//Фамилия
var surname:String,
@ColumnInfo(name = "patronymic")//Отчество
var patronymic:String,
// @ColumnInfo(name = "email")//Логин
// var email:String,
@ColumnInfo(name = "login")//Логин
var login:String,
@ColumnInfo(name = "password")//Пароль
var password:String,
)

View File

@ -0,0 +1,47 @@
package com.example.rehabilitation.Room.dbUser.dbPatient
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoPatient {
//Таблица определенного дня
@Insert
fun insertItemPatient(itemPatient:ItemPatient)
//Список пациентов
@Query("SELECT * FROM Patient ORDER BY id ASC")
fun getAllItemPatient(): Flow<List<ItemPatient>>
//Опредеоение авторизованного пациента
@Query("SELECT * FROM Patient WHERE login = :login AND password = :password")
fun getAuthItemPatient(login:String, password:String): Flow<List<ItemPatient>>
//Опредеоение авторизованного пациента
@Query("SELECT count(*)as id,name,surname,patronymic,diagnosis,number_of_courses,login,password FROM Patient WHERE login = :login AND password = :password")
fun getAuthItemPatient2(login:String, password:String): Flow<List<ItemPatient>>
//Опредеоение авторизованного пациента
@Query("SELECT * FROM Patient WHERE login = :login")
fun getAuthItemPatientOutput(login:String): Flow<List<ItemPatient>>
//Опредеоение авторизованного пациента
@Query("DELETE FROM Patient WHERE login = :login")
fun deletePatient(login:String)
// @Update
// fun updateCheckDaySport(itemPatient: ItemPatient)
//Обновление что выполнил упражнение
@Query("UPDATE Patient SET name = :name, surname = :surname, patronymic= :patronymic,diagnosis=:diagnosis,login=:login,password=:password WHERE login =:loginOld")
fun updatePatient(loginOld:String, name:String,surname:String,patronymic:String,diagnosis:String,login:String,password: String)
@Query("SELECT (SELECT COUNT(*) FROM Patient) == 0")
fun isPatientNull(): Boolean
//Очистка таблицы
// @Query("DELETE FROM Patient")
// fun deleteItemPatient()
}

View File

@ -0,0 +1,28 @@
package com.example.rehabilitation.Room.dbUser.dbPatient
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "Patient")
data class ItemPatient(
@PrimaryKey(autoGenerate = true)
var id:Int? = null,
@ColumnInfo(name = "name")//Имя
var name:String,
@ColumnInfo(name = "surname")//Фамилия
var surname:String,
@ColumnInfo(name = "patronymic")//Отчество
var patronymic:String,
@ColumnInfo(name = "diagnosis")//Диагноз
var diagnosis:String,
@ColumnInfo(name = "number_of_courses")//Дата рождения
var number_of_courses:Int,
// @ColumnInfo(name = "email")//Логин
// var email:String,
@ColumnInfo(name = "login")//Логин
var login:String,
@ColumnInfo(name = "password")//Пароль
var password:String,
)

View File

@ -1,24 +1,25 @@
package com.example.rehabilitation package com.example.rehabilitation
import android.content.Context
import android.content.Intent import android.content.Intent
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import com.example.rehabilitation.Admin.activityAdmin.FeedbackActivity import com.example.rehabilitation.Admin.activityAdmin.FeedbackActivity
import com.example.rehabilitation.Admin.activityAdmin.StatisticsActivity
import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity import com.example.rehabilitation.Admin.activityAdmin.UserSettingActivity
import com.example.rehabilitation.databinding.ActivitySettingBinding import com.example.rehabilitation.databinding.ActivitySettingBinding
import com.example.rehabilitation.Admin.fragmrntAdmin.FeedbackFragment import com.example.rehabilitation.Auth.AuthorizationActivity
import com.example.rehabilitation.Admin.fragmrntAdmin.MainSettingFragment
import com.example.rehabilitation.Admin.fragmrntAdmin.StatisticsFragment
import com.example.rehabilitation.Admin.fragmrntAdmin.UserSettingFragment
class SettingActivity : AppCompatActivity() { class SettingActivity : AppCompatActivity() {
var backPressedTime: Long = 0
private lateinit var binding: ActivitySettingBinding private lateinit var binding: ActivitySettingBinding
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
binding = ActivitySettingBinding.inflate(layoutInflater) binding = ActivitySettingBinding.inflate(layoutInflater)
setContentView(binding.root) setContentView(binding.root)
data_prefUserPatientToken()
// //Выводим фрагмент как экран // //Выводим фрагмент как экран
// supportFragmentManager.beginTransaction() // supportFragmentManager.beginTransaction()
// .replace(R.id.CLMainSetting, MainSettingFragment.newInstance()) // .replace(R.id.CLMainSetting, MainSettingFragment.newInstance())
@ -26,7 +27,9 @@ class SettingActivity : AppCompatActivity() {
binding.btnExitSetting.setOnClickListener { binding.btnExitSetting.setOnClickListener {
val intetn = Intent(this, MainActivity::class.java)
finish() finish()
startActivity(intetn)
} }
binding.cvSettingUser.setOnClickListener{ binding.cvSettingUser.setOnClickListener{
@ -37,15 +40,65 @@ class SettingActivity : AppCompatActivity() {
binding.cvFeedback.setOnClickListener{ binding.cvFeedback.setOnClickListener{
val intent = Intent(this, FeedbackActivity::class.java) val intent = Intent(this, FeedbackActivity::class.java)
startActivity(intent) startActivity(intent)
}
binding.cvStatistics.setOnClickListener{
val intent = Intent(this, StatisticsActivity::class.java)
startActivity(intent)
}
} }
//Выход из аккаунта
binding.cvExitPatient.setOnClickListener{
createAlеrtDialogExitAuth()
}
}
override fun onDestroy() {
super.onDestroy()
finish()
}
//Диалоговое окно
private fun createAlеrtDialogExitAuth() {
val builder = AlertDialog.Builder(this)
builder.setTitle("Выход")
builder.setMessage("Вы уверены что хотите выйти из аккаунта")
builder.setNegativeButton("Назад") { dialogInterface, i ->
}
builder.setPositiveButton("Подтвердить") { dialogInterface, i ->
clearUserPatientToken()
val intetn = Intent(this, AuthorizationActivity::class.java)
finish()
startActivity(intetn)
}
builder.show()
}
//Инициализация хранилища(для токена) и проверяем есть ли аккаунт и или перекидываем в авторизацую или остаемся на данном экране
fun data_prefUserPatientToken() {
prefUserPatientToken = getSharedPreferences("UserPatientToken", Context.MODE_PRIVATE)
UserPatientToken = prefUserPatientToken?.getString("userpatienttoken", "")!! //Передаем при запуске страницы в counter данные по ключевому слову "counter", вс лучае если будет пусто то передастся 0
}
//Записываем число
fun saveUserPatientToken(userpatienttoken: String) {
val editer = prefUserPatientToken?.edit()
editer?.putString("userpatienttoken", userpatienttoken)
editer?.apply()
UserPatientToken = userpatienttoken
}
//Функция очистки данных
fun clearUserPatientToken() {
val edit = prefUserPatientToken?.edit()
edit?.clear()
edit?.apply()
UserPatientToken = ""
}
override fun onBackPressed() {
val intetn = Intent(this, MainActivity::class.java)
startActivity(intetn)
finish()
}
} }

View File

@ -0,0 +1,67 @@
package com.example.rehabilitation.Toast
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import com.example.rehabilitation.R
const val notificationID = 1
const val channelID= "channel1"
const val titleExtra = "titleExtra"
const val messageExtra = "messageExtra"
open class Notification:BroadcastReceiver() {
var manager_: NotificationManager? = null
override fun onReceive(context: Context?, intent: Intent?) {
val notification = context?.let {
NotificationCompat.Builder(it,channelID)
.setSmallIcon(R.drawable.basket_24)
.setContentTitle(intent?.getStringExtra(titleExtra))
.setContentText(intent?.getStringExtra(messageExtra))
.build()
}
val manager = context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(notificationID,notification)
manager_ = manager
}
//Удаление
fun cancel_notification(notificationID:Int){
manager_?.cancel(notificationID)
}
}

View File

@ -0,0 +1,103 @@
package com.example.admin.Toast
import android.app.Activity
import android.view.Gravity
import android.widget.TextView
import android.widget.Toast
import com.example.rehabilitation.R
fun Toast.showCustomToast(message: String, activity: Activity)
{
val layout = activity.layoutInflater.inflate (
R.layout.custom_toast_layout,
activity.findViewById(R.id.toast_container)
)
// set the text of the TextView of the message
val textView = layout.findViewById<TextView>(R.id.toast_text)
//Передача текста который мы введем
textView.text = message
//Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину
/* textView.setOnClickListener{
setToolbarTitle.perehods()
Log.d("dsfsd","111111111111111111111111111")
}*/
// use the application extension function
this.apply {
//setGravity(Gravity.BOTTOM, 0, 40)
duration = Toast.LENGTH_SHORT
view = layout.rootView
show()
}
} fun Toast.showCustomDangerToast(message: String, activity: Activity)
{
val layout = activity.layoutInflater.inflate (
R.layout.custom_toast_layout_danger,
activity.findViewById(R.id.toast_container)
)
// set the text of the TextView of the message
val textView = layout.findViewById<TextView>(R.id.toast_text)
//Передача текста который мы введем
textView.text = message
//Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину
// use the application extension function
this.apply {
setGravity(Gravity.BOTTOM, 0, 40)
duration = Toast.LENGTH_SHORT
view = layout.rootView
show()
}
}
fun Toast.showCustomInfoToast(message: String, activity: Activity) {
val layout = activity.layoutInflater.inflate(
R.layout.custom_toast_layout_info,
activity.findViewById(R.id.toast_container)
)
// set the text of the TextView of the message
val textView = layout.findViewById<TextView>(R.id.toast_text)
//Передача текста который мы введем
textView.text = message
//Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину
// use the application extension function
this.apply {
setGravity(Gravity.BOTTOM, 0, 40)
duration = Toast.LENGTH_SHORT
view = layout.rootView
show()
}
}
fun Toast.showCustomNiceToast(message: String, activity: Activity) {
val layout = activity.layoutInflater.inflate(
R.layout.custom_toast_layout_nice,
activity.findViewById(R.id.toast_container)
)
// set the text of the TextView of the message
val textView = layout.findViewById<TextView>(R.id.toast_text)
//Передача текста который мы введем
textView.text = message
//Если добавить кнопку то можно сделать некую функцию, к примеру при добавление товара в корзину, можно сверху выводить перейти в корзину и по нажатию мы переходим в корзину
// use the application extension function
this.apply {
setGravity(Gravity.BOTTOM, 0, 40)
duration = Toast.LENGTH_SHORT
view = layout.rootView
show()
}
}

View File

@ -1,46 +1,50 @@
package com.example.rehabilitation.User.fragmentUser package com.example.rehabilitation.User.fragmentUser
import android.content.ContentResolver //import ru.cleverpumpkin.calendar.CalendarDate
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import android.util.Log import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.CalendarView import android.widget.CalendarView
import android.widget.Toast import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData import androidx.lifecycle.asLiveData
import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager
import com.example.rehabilitation.BuildConfig import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.databinding.FragmentCalendarBinding import com.example.rehabilitation.databinding.FragmentCalendarBinding
import com.example.rehabilitation.db.MainDB import com.example.rehabilitation.dateHomeCalendare
import com.example.rehabilitation.dip.Day.DayAdapter import com.example.rehabilitation.model_adapter.DataModel
import com.example.rehabilitation.dip.Day.DayModel import com.example.rehabilitation.model_adapter.Day.DayAdapter
import com.example.rehabilitation.model_adapter.Day.DayListModel
import com.example.sqlitework.dip.MainViewModel import com.example.sqlitework.dip.MainViewModel
import java.time.LocalDate import java.time.LocalDate
import java.util.Calendar import java.util.Calendar
class CalendarFragment : Fragment(),DayAdapter.Listener { class CalendarFragment : Fragment(), DayAdapter.Listener {
private lateinit var binding: FragmentCalendarBinding private lateinit var binding: FragmentCalendarBinding
lateinit var adapterDay: DayAdapter lateinit var adapterDay: DayAdapter
private val model: MainViewModel by activityViewModels()//Инициализировали класс private val model: MainViewModel by activityViewModels()//Инициализировали класс
private val dataModel: DataModel by activityViewModels()//Для передачи данных
var visibleCalendar = true
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle? savedInstanceState: Bundle?
): View? { ): View? {
binding = FragmentCalendarBinding.inflate(layoutInflater,container,false) binding = FragmentCalendarBinding.inflate(layoutInflater, container, false)
return binding.root return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
initRcViewDay() initRcViewDay()
liveReadOrderDayCurrent() //liveReadOrderDayCurrent()
model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter) adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter)
} }
@ -56,29 +60,103 @@ class CalendarFragment : Fragment(),DayAdapter.Listener {
// Now set calenderView with this calender object to highlight selected date on UI. // Now set calenderView with this calender object to highlight selected date on UI.
calView.setDate(calender.timeInMillis, true, true) calView.setDate(calender.timeInMillis, true, true)
Log.d("SelectedDate", "${LocalDate.of(year, month+1, dayOfMonth)}") Log.d("SelectedDate", "${LocalDate.of(year, month + 1, dayOfMonth)}")
if(LocalDate.of(year, month+1, dayOfMonth).toString() == LocalDate.now().toString()){ if (LocalDate.of(year, month + 1, dayOfMonth).toString() > LocalDate.now().toString()) {
addListModelCardsDay("${LocalDate.of(year, month+1, dayOfMonth)}")
}
else{
Toast.makeText(requireContext(), "Ошибка", Toast.LENGTH_SHORT).show() Toast.makeText(requireContext(), "Ошибка", Toast.LENGTH_SHORT).show()
} else {
addListModelCardsDay("${LocalDate.of(year, month + 1, dayOfMonth)}")
} }
} }
//addListModelCardsDay("2023-7-13")
val fileName = "b3_1.png"
val fileUri = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://"+ BuildConfig.APPLICATION_ID+"/drawable/${fileName}") binding.btnVisible.setOnClickListener {
val filePath = fileUri.path if (visibleCalendar == true) {
binding.CLCalendar.visibility = View.GONE
visibleCalendar = false
binding.btnVisible.setBackgroundResource(R.drawable.visible_eas_false)
} else if (visibleCalendar == false){
binding.CLCalendar.visibility = View.VISIBLE
visibleCalendar = true
binding.btnVisible.setBackgroundResource(R.drawable.visible_eas_true)
}
}
// val fileName1 = "my_image.png" // calendarV2()
// val inputStream1 = assets.open("drawable/${fileName}") calendarV3()
// val filePath1 = inputStream.toString()
// val resourceId12 = R.drawable.b3_1 }
// val fileUri12 = Uri.parse("android.resource://"+ BuildConfig.APPLICATION_ID+"/${resourceId12}")
// val filePath12 = fileUri12.path private fun calendarV3() {
//
// binding.fabButton.setOnClickListener { openDatePicker() }
// binding.calendarViewV3.setOnDayClickListener(requireContext())
// val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_calendar_horizontal, parent, false)
// return MonthCalendarViewHolder(view)
}
private fun calendarV2() {
// val calendarView = binding.calendarViewV2
// val calendar = Calendar.getInstance()
//// var dates = ArrayList<CalendarDate>()
//// dates.add(LocalDate.now().dayOfMonth)
//// Initial date
// calendar.set(2023, Calendar.JUNE, 1 )
// val initialDate = CalendarDate(calendar.time)
//
//// Minimum available date
// calendar.set(2023, Calendar.MAY, 1)
// val minDate = CalendarDate(calendar.time)
//
//// Maximum available date
// calendar.set(2023, Calendar.JULY, 15)
// val maxDate = CalendarDate(calendar.time)
//
//// List of preselected dates that will be initially selected
// //val preselectedDates: List<CalendarDate> = ru.cleverpumpkin.calendar.getPreselectedDates()
//
//// The first day of week
// val firstDayOfWeek = java.util.Calendar.MONDAY
//
//// Set up calendar with all available parameters
// calendarView.setupCalendar(
// initialDate = initialDate,
// minDate = minDate,
// maxDate = maxDate,
// selectionMode = ru.cleverpumpkin.calendar.CalendarView.SelectionMode.NONE,
// //selectedDates = preselectedDates,
// firstDayOfWeek = firstDayOfWeek,
// showYearSelectionView = true
// )
// // Set up calendar
// calendarView.setupCalendar()
//// Set up calendar
// calendarView.setupCalendar()
//
//
// val additionalTexts: List<ru.cleverpumpkin.calendar.CalendarView.AdditionalText> = generateAdditionalTexts()
//
//// Set List of additional texts that will be displayed on the calendar
// calendarView.datesAdditionalTexts = additionalTexts
//
//
//// Set List of indicators that will be displayed on the calendar
// //calendarView.datesIndicators = indicators
}
fun ClearRCView(){
adapterDay.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
initRcViewDay()
}
override fun onResume() {
super.onResume()
//ClearRCView()
//addListModelCardsDay("${LocalDate.now()}")
}
override fun onDestroy() {
super.onDestroy()
adapterDay.notifyDataSetChanged()
ClearRCView()
// binding.imageView4.setImageResource(filePath12!!.toInt())
} }
//Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта //Функция запускающая отслеживания за списком, чтобы вовремя обновлять основную карточку продукта
@ -87,46 +165,52 @@ class CalendarFragment : Fragment(),DayAdapter.Listener {
} }
} }
//Инициализация списка //Инициализация списка
private fun initRcViewDay() = with(binding) { private fun initRcViewDay() = with(binding) {
rcViewDayCalendar.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию rcViewDayCalendar.layoutManager = GridLayoutManager(requireContext(), 1)//По вертикали будет выводить по умолчанию
adapterDay = DayAdapter(this@CalendarFragment) adapterDay = DayAdapter(this@CalendarFragment)
rcViewDayCalendar.adapter = adapterDay rcViewDayCalendar.adapter = adapterDay
} }
//Заполнения модели и списка
private fun addListModelCardsDay(day:String){ private fun addListModelCardsDay(day: String) {
val db = MainDB.getDB(requireContext()) val db = MainDB.getDB(requireContext())
val list = ArrayList<DayModel>() val list = ArrayList<DayListModel>()
db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList-> db.getDaoDaySport().getAllItemDaySport(day).asLiveData()
var number = 0; .observe(requireActivity()) { itList ->
itList.forEach{ var number = 1;
//val text = "Id: ${it.id} Name: ${it.name} Proce: ${it.price}"
//binding.txtList.append(text) itList.forEach {
val itemDay = DayModel( Log.d("123", it.category)
//db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport->
val itemDay = DayListModel(
it.id.toString(), it.id.toString(),
//it.name.toString(), number++.toString(),
//it.desc.toString(), day,
"123",
"321",
it.day.toString(),
(number++).toString(),
it.category.toString(), it.category.toString(),
//it.count.toString(),
//it.image.toString(),
it.check.toString(), it.check.toString(),
) )
//model.liveZakazCurrent.value = item//Передаем в liveDataCurrent один из продуктов, чтобы дальше эти данные использовать и передавать их в пробную ячейку
list.add(itemDay)//Передали заполненый список list.add(itemDay)//Передали заполненый список
}
model.liveDayList.value = list model.liveDayList.value = list
//}
}
Log.d("sadas", list.toString())
} }
} }
companion object { companion object {
fun newInstance() = CalendarFragment() fun newInstance() = CalendarFragment()
} }
override fun onClickDay(item: DayModel) {
override fun onClickDay(item: DayListModel) {
dataModel.fragmentMenu.value = R.id.schedule
dateHomeCalendare = item.day
} }
} }

View File

@ -1,14 +1,38 @@
package com.example.rehabilitation.User.fragmentUser package com.example.rehabilitation.User.fragmentUser
import android.os.Bundle import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.asLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.example.rehabilitation.model_adapter.Edit.adapterFirebase.ReportPatient
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.checkDaySportString
import com.example.rehabilitation.countCategory
import com.example.rehabilitation.databinding.FragmentHomeBinding import com.example.rehabilitation.databinding.FragmentHomeBinding
import com.example.rehabilitation.dateHomeCalendare
import com.example.rehabilitation.loginDoctor
import com.example.rehabilitation.loginPatient
import com.example.rehabilitation.model_adapter.DataModel
import com.example.rehabilitation.model_adapter.Day.DayAdapter
import com.example.rehabilitation.model_adapter.Day.DayListModel
import com.example.rehabilitation.model_adapter.modelCount.CountDayModel
import com.example.rehabilitation.model_adapter.modelCount.CountMonthModel
import com.example.sqlitework.dip.MainViewModel
import java.time.LocalDate
class HomeFragment : Fragment() { class HomeFragment : Fragment(),DayAdapter.Listener {
private lateinit var binding: FragmentHomeBinding private lateinit var binding: FragmentHomeBinding
private val model: MainViewModel by activityViewModels()//Инициализировали класс
lateinit var adapterDay: DayAdapter
//private val dataModel: DataModel by activityViewModels()//Для передачи данных
private val dataModel: DataModel by activityViewModels()//Для передачи данных
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle? savedInstanceState: Bundle?
@ -17,8 +41,106 @@ class HomeFragment : Fragment() {
return binding.root return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initRcViewDay()
model.liveDayList.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
adapterDay.submitList(it)//Напрямую переадем созданный список в adapter(ProductAdapter)
}
progresMonthAndDay()
liveCountDayCurrent()
addListModelCardsDay(LocalDate.now().toString())
// dataModel.fragmentMenu.observe(this as LifecycleOwner, {
// binding.buttonNavigation.selectedItemId = it
// })
}
//Заполнения модели и списка
private fun addListModelCardsDay(day:String){
val db = MainDB.getDB(requireContext())
val list = ArrayList<DayListModel>()
db.getDaoDaySport().getAllItemDaySport(day).asLiveData().observe(requireActivity()){itList->
var number = 1;
itList.forEach{
Log.d("123",it.category)
//db.getDaoSportCategory().getAllItemsSportCategory(it.category).asLiveData().observe(requireActivity()){itSport->
val itemDay = DayListModel(
it.id.toString(),
number++.toString(),
day,
it.category.toString(),
it.check.toString(),
)
list.add(itemDay)//Передали заполненый список
model.liveDayList.value = list
//}
}
Log.d("sadas",list.toString())
}
}
private fun progresMonthAndDay() {
val db = MainDB.getDB(requireContext())
val data= LocalDate.now().toString()
var listDayDown =0
var listDayAll =0
var name = ""
//Прогрес за в течение данного дня
db.getDaoDaySport().getAllItemDaySport(LocalDate.now().toString()).asLiveData().observe(requireActivity()){itList->
var number = 1;
itList.forEach{
if(it.check ==1){
listDayDown=listDayDown+1
listDayAll=listDayAll+1
}
else{
listDayAll=listDayAll+1
}
}
val item = CountDayModel(
listDayDown,
listDayAll
)
model.liveCountDayCurrent.value = item
}
}
//Вывод прогресса на один день
private fun liveCountDayCurrent() = with(binding) {
model.liveCountDayCurrent.observe(viewLifecycleOwner) {//viewLifecycleOwner - следит за циклом жизни fragment
binding.txtSportToday.setText(it.countDown.toString())
binding.txtSportTodayAll.setText(it.countAll.toString())
}
}
//Инициализация списка
private fun initRcViewDay() = with(binding) {
rcVIewDayList.layoutManager = GridLayoutManager(requireContext(),1)//По вертикали будет выводить по умолчанию
adapterDay = DayAdapter(this@HomeFragment)
rcVIewDayList.adapter = adapterDay
}
companion object { companion object {
fun newInstance() = HomeFragment() fun newInstance() = HomeFragment()
} }
override fun onClickDay(item: DayListModel) {
//Передаем фрагмент на вывод(это фрагмент страницы с продукцией)
//parentFragmentManager.beginTransaction() .replace(R.id.placeHolderFragment, SceduleFragment()).commit()
dataModel.fragmentMenu.value = R.id.schedule
dateHomeCalendare = item.day
}
} }

View File

@ -0,0 +1,37 @@
package com.example.rehabilitation.fragment.InfoFragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentCommonInfoBinding
class CommonInfoFragment : Fragment() {
private lateinit var binding: FragmentCommonInfoBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentCommonInfoBinding.inflate(inflater, container, false)
return binding.root
}
// override fun onResume() {
// super.onResume()
// binding.CLCommonInfo.visibility = View.VISIBLE
// }
//
// override fun onDestroy() {
// super.onDestroy()
// binding.CLCommonInfo.visibility = View.GONE
//
// }
companion object {
@JvmStatic
fun newInstance() = CommonInfoFragment()
}
}

View File

@ -0,0 +1,38 @@
package com.example.rehabilitation.fragment.InfoFragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentMedicalReabilitationBinding
class MedicalReabilitationFragment : Fragment() {
private lateinit var binding: FragmentMedicalReabilitationBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentMedicalReabilitationBinding.inflate(inflater, container, false)
return inflater.inflate(R.layout.fragment_medical_reabilitation, container, false)
}
// override fun onResume() {
// super.onResume()
// binding.CLMadicalReabilitation.visibility = View.VISIBLE
// }
//
// override fun onDestroy() {
// super.onDestroy()
// binding.CLMadicalReabilitation.visibility = View.GONE
//
// }
companion object {
@JvmStatic
fun newInstance() = MedicalReabilitationFragment()
}
}

View File

@ -0,0 +1,40 @@
package com.example.rehabilitation.fragment.InfoFragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentFaqBinding
class faqFragment : Fragment() {
private lateinit var binding: FragmentFaqBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding = FragmentFaqBinding.inflate(inflater, container, false)
return binding.root
}
// override fun onResume() {
// super.onResume()
// binding.CLFaq.visibility = View.VISIBLE
// }
//
// override fun onDestroy() {
// super.onDestroy()
// binding.CLFaq.visibility = View.GONE
//
// }
companion object {
@JvmStatic
fun newInstance() = faqFragment()
}
}

View File

@ -1,11 +1,19 @@
package com.example.rehabilitation.User.fragmentUser package com.example.rehabilitation.User.fragmentUser
import android.content.Intent
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import com.example.rehabilitation.Auth.AuthDoctorActivity
import com.example.rehabilitation.MainActivity
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.FragmentInformationBinding import com.example.rehabilitation.databinding.FragmentInformationBinding
import com.example.rehabilitation.fragment.InfoFragment.CommonInfoFragment
import com.example.rehabilitation.fragment.InfoFragment.MedicalReabilitationFragment
import com.example.rehabilitation.fragment.InfoFragment.faqFragment
class InformationFragment : Fragment() { class InformationFragment : Fragment() {
@ -18,6 +26,60 @@ class InformationFragment : Fragment() {
return binding.root return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.commonInformationButton.setOnClickListener {
val infoFrag = activity?.supportFragmentManager?.beginTransaction()
infoFrag?.replace(R.id.CLInformation, CommonInfoFragment.newInstance())
infoFrag?.addToBackStack(null)
infoFrag?.commit()
}
binding.frequentlyAskedQuestionsButton.setOnClickListener {
val infoFrag = activity?.supportFragmentManager?.beginTransaction()
infoFrag?.replace(R.id.CLInformation, faqFragment.newInstance())
infoFrag?.addToBackStack(null)
infoFrag?.commit()
}
binding.medicalReabilitationButton.setOnClickListener {
val infoFrag = activity?.supportFragmentManager?.beginTransaction()
infoFrag?.replace(R.id.CLInformation, MedicalReabilitationFragment.newInstance())
infoFrag?.addToBackStack(null)
infoFrag?.commit()
}
binding.fondButton.setOnClickListener{
val i = Intent(Intent.ACTION_VIEW, Uri.parse("https://фонд-защитники-отечества.рф/filials"))
startActivity(i)
}
//Выход со страницы
binding.btnExitInformation.setOnClickListener {
val intetn = Intent(requireContext(), MainActivity::class.java)
startActivity(intetn)
activity?.finish()
}
}
// override fun onDestroy() {
// super.onDestroy()
// activity?.finish()
//
// binding.CLFragmentInformation.visibility = View.GONE
// }
//
// override fun onResume() {
// super.onResume()
// binding.CLFragmentInformation.visibility = View.VISIBLE
//
// }
companion object { companion object {
fun newInstance() = InformationFragment() fun newInstance() = InformationFragment()

View File

@ -0,0 +1,681 @@
package com.example.rehabilitation.User.fragmentUser.QuestionnaireFragment
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.admin.Toast.showCustomInfoToast
import com.example.admin.Toast.showCustomNiceToast
import com.example.rehabilitation.Block
import com.example.rehabilitation.DayAfter
import com.example.rehabilitation.DayBefore
import com.example.rehabilitation.PauseDay
import com.example.rehabilitation.R
import com.example.rehabilitation.Room.MainDB
import com.example.rehabilitation.Room.Questionnaire.After.ItemAfterQuestionnaire
import com.example.rehabilitation.Room.Questionnaire.Before.ItemBeforeQuestionnaire
import com.example.rehabilitation.Sport15Day
import com.example.rehabilitation.Sport15DayAll
import com.example.rehabilitation.Sport7Day
import com.example.rehabilitation.SportCursDay
import com.example.rehabilitation.SportCursDayDangerAfter
import com.example.rehabilitation.SportCursDayDangerBefore
import com.example.rehabilitation.SportCursDayNumber
import com.example.rehabilitation.SportPlusCount
import com.example.rehabilitation.User.fragmentUser.SceduleFragment
import com.example.rehabilitation.countSport
import com.example.rehabilitation.databinding.FragmentQAfterBinding
import com.example.rehabilitation.prefBlock
import com.example.rehabilitation.prefCursDangerDayAfter
import com.example.rehabilitation.prefCursDangerDayBefore
import com.example.rehabilitation.prefCursDay
import com.example.rehabilitation.prefDayAfter
import com.example.rehabilitation.prefDayBefore
import com.example.rehabilitation.prefPauseDay
import com.example.rehabilitation.prefSport15Day
import com.example.rehabilitation.prefSport15DayAll
import com.example.rehabilitation.prefSport7Day
import com.example.rehabilitation.prefSportCursDayNumber
import com.example.rehabilitation.questionnaire_after
import com.example.rehabilitation.questionnaire_before
import java.time.LocalDate
class QAfterFragment : Fragment() {
private lateinit var binding: FragmentQAfterBinding
var one = ""
var two = ""
var thee = ""
var four = ""
var five = ""
var six = ""
var seven = ""
var eight = ""
var nine = ""
var ten = ""
var eleven = ""
var twelve = ""
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentQAfterBinding.inflate(layoutInflater, container, false)
return binding.root
}
companion object {
fun newInstance() = QAfterFragment()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d("lookDanger", "lookDanger")
Log.d("SportCursDayDangerAfter", "${SportCursDayDangerAfter}")
Log.d("SportCursDay", "${SportCursDay}")
Log.d("SportCursDayDangerBefore", "${SportCursDayDangerBefore}")
prefCursDay = activity?.getSharedPreferences("SportCursDay", Context.MODE_PRIVATE)
SportCursDay = prefCursDay?.getInt("scd", 0)!!
prefCursDangerDayAfter =
activity?.getSharedPreferences("CursDangerDayAfter", Context.MODE_PRIVATE)
SportCursDayDangerAfter = prefCursDangerDayAfter?.getInt("cdda", 0)!!
prefCursDangerDayBefore =
activity?.getSharedPreferences("CursDangerDayBefore", Context.MODE_PRIVATE)
SportCursDayDangerBefore = prefCursDangerDayBefore?.getInt("cddb", 0)!!
//Какой сегодня курс
prefSportCursDayNumber =
activity?.getSharedPreferences("SportCursDayNumber", Context.MODE_PRIVATE)
SportCursDayNumber = prefSportCursDayNumber?.getInt("scdn", 0)!!
//Для анкет, какие выполнены
prefPauseDay = activity?.getSharedPreferences("PauseDay", Context.MODE_PRIVATE)
PauseDay = prefPauseDay?.getString("pd", "")!!
prefBlock = activity?.getSharedPreferences("Block", Context.MODE_PRIVATE)
Block = prefBlock?.getString("b", "")!!
//Для анкет, какие выполнены
prefDayBefore = activity?.getSharedPreferences("DayBefore", Context.MODE_PRIVATE)
DayBefore = prefDayBefore?.getString("db", "")!!
prefDayAfter = activity?.getSharedPreferences("DayAfter", Context.MODE_PRIVATE)
DayAfter = prefDayAfter?.getString("da", "")!!
//Пройдено ли 15 дне и отправен отчет
prefSport15DayAll = activity?.getSharedPreferences("Sport15DayAll", Context.MODE_PRIVATE)
Sport15DayAll = prefSport15DayAll?.getInt("s15da", 0)!!
//Отчет на 15 день
prefSport15Day = activity?.getSharedPreferences("Sport15Day", Context.MODE_PRIVATE)
Sport15Day = prefSport15Day?.getInt("s15d", 0)!!
//Отчет на 7 день
prefSport7Day = activity?.getSharedPreferences("Sport7Day", Context.MODE_PRIVATE)
Sport7Day = prefSport7Day?.getInt("s7d", 0)!!
buttenAdd()
//Выход
binding.btnBack.setOnClickListener {
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit()
}
//Сохраняем результат
binding.btnSaveQuestionnaire.setOnClickListener {
if (one != "" && two != "" && thee != "" && four != "" && five != "" && six != "" && seven != "" && eight != "" && nine != "" && ten != "" && eleven != "" && twelve != "") {
if(ten == "1"){
AlertDialog.Builder(requireContext())
.setTitle("Анкета")
.setMessage("Вы уверенны в выбронных пунктах анкеты? Если вы нажмете 'Подтвердить' ваш курс временно заблакируется, чтобы вы не нанесли вред своему здоровью")
.setNeutralButton("Подтвердить") { dialog, whichButton ->
addQuestionnaire()
}
.setNegativeButton("Отмена") { dialog, whichButton ->
}
.show()
}
else{
addQuestionnaire()
}
} else {
Toast(requireContext()).showCustomInfoToast(
"Не все пункты выбраны",
requireActivity()
)
}
}
}
//Функция
fun addQuestionnaire(){
clearSportCursDayDangerBefore()
if(ten == "1"){
saveBlock(LocalDate.now().plusDays(3).toString())
saveSportCursDayDangerAfter(2)
Log.d("saveSportCursDayDangerAfter","${2}")
addQuestionAfter()
}
else if (one >= "6" || thee == "0"||six == "1"||eight == "1"||eleven == "1") {
savePauseDay(LocalDate.now().plusDays(1).toString())
saveSportCursDayDangerAfter(1)
addQuestionAfter()
}
else{
clearSportCursDayDangerBefore()
clearSportCursDayDangerAfter()
addQuestionAfter()
}
}
fun addQuestionAfter() {
val db = MainDB.getDB(requireContext())
val item = ItemAfterQuestionnaire(
null,
one,
two,
thee,
four,
five,
six,
seven,
eight,
nine,
ten,
eleven,
twelve,
LocalDate.now().toString()
)
Thread {
db.getDaoQA().insertAQ(item)
db.getDao().updateDay(LocalDate.now().toString(), (SportCursDay - 1).toString())
}.start()
saveDayAfter(LocalDate.now().toString())
if (SportCursDay == 7 && Sport7Day == 0) {
saveSport7Day(1)
} else if (SportCursDay == 15 && Sport15Day == 0) {
saveSport15Day(1)
}
// questionnaire_after = LocalDate.now().toString()
// questionnaire_before = LocalDate.now().toString()
// //QBSaveDataB(LocalDate.now().toString())
// //Log.d("aaaaaa",questionnaire?.getString("QB", "")!!.toString())
activity?.supportFragmentManager?.beginTransaction()
?.replace(R.id.placeHolderFragment, SceduleFragment.newInstance())?.commit()
}
fun saveSport15Day(s15d: Int) {
val edit = prefSport15Day?.edit()
edit?.putInt("s15d", s15d)
edit?.apply()
Sport15Day = s15d
}
fun clearSport15Day() {
val edit = prefSport15Day?.edit()
edit?.clear()
edit?.apply()
Sport15Day = 0
}
fun saveSport7Day(s7d: Int) {
val edit = prefSport7Day?.edit()
edit?.putInt("s7d", s7d)
edit?.apply()
Sport7Day = s7d
}
fun clearSport7Day() {
val edit = prefSport7Day?.edit()
edit?.clear()
edit?.apply()
Sport7Day = 0
}
fun savePauseDay(pd: String) {
val edit = prefPauseDay?.edit()
edit?.putString("pd", pd)
edit?.apply()
PauseDay = pd
}
fun clearPauseDay() {
val edit = prefPauseDay?.edit()
edit?.clear()
edit?.apply()
PauseDay = ""
}
fun saveBlock(b: String) {
val edit = prefBlock?.edit()
edit?.putString("b", b)
edit?.apply()
Block = b
}
fun clearBlock() {
val edit = prefBlock?.edit()
edit?.clear()
edit?.apply()
Block = ""
}
fun saveDayBefore(db: String) {
val edit = prefDayBefore?.edit()
edit?.putString("db", db)
edit?.apply()
DayBefore = db
}
fun clearDayBefore() {
val edit = prefDayBefore?.edit()
edit?.clear()
edit?.apply()
DayBefore = ""
}
fun saveDayAfter(da: String) {
val edit = prefDayAfter?.edit()
edit?.putString("da", da)
edit?.apply()
DayAfter = da
}
fun clearDayAfter() {
val edit = prefDayAfter?.edit()
edit?.clear()
edit?.apply()
DayAfter = ""
}
fun saveSportCursDay(scd: Int) {
val edit = prefCursDay?.edit()
edit?.putInt("scd", scd)
edit?.apply()
SportCursDay = scd
}
fun clearSportCursDay() {
val edit = prefCursDay?.edit()
edit?.clear()
edit?.apply()
SportCursDay = 0
}
fun saveSportCursDayDangerBefore(cddb: Int) {
val edit = prefCursDangerDayBefore?.edit()
edit?.putInt("cddb", cddb)
edit?.apply()
SportCursDayDangerBefore = cddb
}
fun clearSportCursDayDangerBefore() {
val edit = prefCursDangerDayBefore?.edit()
edit?.clear()
edit?.apply()
SportCursDayDangerBefore = 0
}
fun saveSportCursDayDangerAfter(cdda: Int) {
val edit = prefCursDangerDayAfter?.edit()
edit?.putInt("cdda", cdda)
edit?.apply()
SportCursDayDangerAfter = cdda
}
fun clearSportCursDayDangerAfter() {
val edit = prefCursDangerDayAfter?.edit()
edit?.clear()
edit?.apply()
SportCursDayDangerAfter = 0
}
private fun buttenAdd() {
buttenAdd1()
buttenAdd2()
buttenAdd3()
buttenAdd4()
buttenAdd5()
buttenAdd6()
buttenAdd7()
buttenAdd8()
buttenAdd9()
buttenAdd10()
buttenAdd11()
buttenAdd12()
}
private fun buttenAdd1() {
binding.CVQ10.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "0"
}
binding.CVQ11.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "1"
}
binding.CVQ12.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "2"
}
binding.CVQ13.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "3"
}
binding.CVQ14.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "4"
}
binding.CVQ15.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "5"
}
binding.CVQ16.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "6"
}
binding.CVQ17.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "7"
}
binding.CVQ18.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "8"
}
binding.CVQ19.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
one = "9"
}
binding.CVQ110.setOnClickListener {
binding.CVQ10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ13.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ14.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ15.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ16.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ17.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ18.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ19.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQ110.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
one = "10"
}
}
private fun buttenAdd2() {
binding.CVQyes2.setOnClickListener {
binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno2.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
two = "1"
}
binding.CVQno2.setOnClickListener {
binding.CVQyes2.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno2.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
two = "0"
}
}
private fun buttenAdd3() {
binding.CVQyes3.setOnClickListener {
Log.d("CVQyes3", "CVQyes3")
binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno3.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
thee = "1"
}
binding.CVQno3.setOnClickListener {
binding.CVQyes3.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno3.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
thee = "0"
}
}
private fun buttenAdd4() {
binding.CVQyes4.setOnClickListener {
binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno4.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
four = "1"
}
binding.CVQno4.setOnClickListener {
binding.CVQyes4.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno4.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
four = "0"
}
}
private fun buttenAdd5() {
binding.CVQyes5.setOnClickListener {
binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno5.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
five = "1"
}
binding.CVQno5.setOnClickListener {
binding.CVQyes5.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno5.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
five = "0"
}
}
private fun buttenAdd6() {
binding.CVQyes6.setOnClickListener {
binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno6.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
six = "1"
}
binding.CVQno6.setOnClickListener {
binding.CVQyes6.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno6.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
six = "0"
}
}
private fun buttenAdd7() {
binding.CVQyes7.setOnClickListener {
binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno7.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
seven = "1"
}
binding.CVQno7.setOnClickListener {
binding.CVQyes7.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno7.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
seven = "0"
}
}
private fun buttenAdd8() {
binding.CVQyes8.setOnClickListener {
binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno8.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
eight = "1"
}
binding.CVQno8.setOnClickListener {
binding.CVQyes8.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno8.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
eight = "0"
}
}
private fun buttenAdd9() {
binding.CVQyes9.setOnClickListener {
binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno9.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
nine = "1"
}
binding.CVQno9.setOnClickListener {
binding.CVQyes9.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno9.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
nine = "0"
}
}
private fun buttenAdd10() {
binding.CVQyes10.setOnClickListener {
binding.CVQyes10.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
ten = "1"
}
binding.CVQno10.setOnClickListener {
binding.CVQyes10.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno10.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
ten = "0"
}
}
private fun buttenAdd11() {
binding.CVQyes11.setOnClickListener {
binding.CVQyes11.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
eleven = "1"
}
binding.CVQno11.setOnClickListener {
binding.CVQyes11.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno11.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
eleven = "0"
}
}
private fun buttenAdd12() {
binding.CVQyes12.setOnClickListener {
binding.CVQyes12.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
binding.CVQno12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
twelve = "1"
}
binding.CVQno12.setOnClickListener {
binding.CVQyes12.setCardBackgroundColor(Color.parseColor("#A8A8A8"))
binding.CVQno12.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
twelve = "0"
}
}
// fun QBSaveDataA(date: String) {
// val QB = questionnaire?.edit()
// QB?.putString("QA", date)
// QB?.apply()
// }
}

View File

@ -1,26 +0,0 @@
package com.example.rehabilitation.db
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface DaoDaySport {
//Таблица определенного дня
@Insert
fun insertItemDaySport(itemDaySport:ItemDaySport)
//Список определенного дня
@Query("SELECT * FROM itemDaySport ORDER BY id ASC")
fun getAllItemDaySport(): Flow<List<ItemDaySport>>
//Список определенного дня
@Query("SELECT * FROM itemDaySport WHERE day = :day ORDER BY id ASC")
fun getAllItemDaySport(day:String): Flow<List<ItemDaySport>>
//Очистка таблицы
@Query("DELETE FROM itemDaySport")
fun deleteItemDaySport()
}

View File

@ -1,23 +0,0 @@
package com.example.rehabilitation.db
import androidx.room.Room
import androidx.room.RoomDatabase
import android.content.Context
import androidx.room.Database
@Database(entities = [Item::class, ItemDaySport::class, ItemImage::class, ItemSportCategory::class], version = 1)
abstract class MainDB: RoomDatabase() {
abstract fun getDao(): Dao
abstract fun getDaoDaySport(): DaoDaySport
abstract fun getDaoImage(): DaoImage
abstract fun getDaoSportCategory(): DaoSportCategory
companion object{
fun getDB(context: Context):MainDB{
return Room.databaseBuilder(
context.applicationContext,
MainDB::class.java,
"tttttttttttttt1.db"
).build()
}
}
}

View File

@ -1,25 +0,0 @@
package com.example.sqlitework.dip
import android.app.Application
import androidx.lifecycle.*
import com.example.rehabilitation.dip.Day.DayModel
import com.example.rehabilitation.dip.Image.ImageSportModel
import com.example.rehabilitation.dip.Month.MonthModel
//Тут будут обновлятся данные, следим за списками если что-то обновилось, то уведомлякм и потом ProductAdapter обновит
class MainViewModel(application: Application) :AndroidViewModel(application){
//Объявления
val liveListCurrent = MutableLiveData<MonthModel>()//Сюда передается новая информация на один день(для слайдера)
val liveListList= MutableLiveData<List<MonthModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveDayCurrent = MutableLiveData<DayModel>()//Сюда передается новая информация на один день(для слайдера)
val liveDayList= MutableLiveData<List<DayModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveImageCurrent = MutableLiveData<ImageSportModel>()//Сюда передается новая информация на один день(для слайдера)
val liveImageList= MutableLiveData<List<ImageSportModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
}

View File

@ -0,0 +1,28 @@
package com.example.rehabilitation.model_adapter
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
//Ослеживание за обновлением подробной продуктовой карточкой
open class DataModel: ViewModel() {
/*//Для отлеживания обновлений активити
val messageForActivity: MutableLiveData<String> by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData<String>()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным
MutableLiveData<String>()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити
}*/
//Для отлеживания обновлений фрагммента 1
val messageForFrag1: MutableLiveData<Int> by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData<String>()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным
MutableLiveData<Int>()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити
}
val fragmentMenu: MutableLiveData<Int> by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData<String>()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным
MutableLiveData<Int>()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити
}
val addZakaz: MutableLiveData<Int> by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData<String>()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным
MutableLiveData<Int>()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити
}
/*//Для отлеживания обновлений фрагммента 2
val messageForFrag2: MutableLiveData<String> by lazy{//by lazy - чтобы каждый раз не создавался MutableLiveData(MutableLiveData<String>()), а он один раз при загрузке создаться и дальше будет пользоваться уже созданным
MutableLiveData<String>()//LiveData - означает что будет обновляться в нужынй момент, не постоянна, а в зависимоти от жизни активити
}*/
}

View File

@ -1,5 +1,8 @@
package com.example.rehabilitation.dip.Day package com.example.rehabilitation.model_adapter.Day
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Handler
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -7,11 +10,10 @@ import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.RcItemBinding
import com.example.rehabilitation.databinding.RcItemDayBinding import com.example.rehabilitation.databinding.RcItemDayBinding
class DayAdapter(val listener_zakaz: Listener) : ListAdapter<DayModel, DayAdapter.Holder>( class DayAdapter(val listener_zakaz: Listener) : ListAdapter<DayListModel, DayAdapter.Holder>(
Comparator() Comparator()
) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку ) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку
@ -22,28 +24,66 @@ class DayAdapter(val listener_zakaz: Listener) : ListAdapter<DayModel, DayAdapte
val binding = RcItemDayBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки val binding = RcItemDayBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки
var itemTemp: DayModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия var itemTemp: DayListModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия
//init - дает возможность внутри адаптера обращаться к элементам экрана //init - дает возможность внутри адаптера обращаться к элементам экрана
init { init {
itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка
itemView.setEnabled(false)
timerButtonDoubleButton(itemView)
itemTemp?.let { it1 -> listener_zakaz.onClickDay(it1) } itemTemp?.let { it1 -> listener_zakaz.onClickDay(it1) }
} }
} }
//Функция bind для заполнения //Функция bind для заполнения
fun bind(item: DayModel) = with(binding) {//Productitem - перпедаем данные
//ЗАдержка нажатия на кнопку
private fun timerButtonDoubleButton(btn: View){
val updateHandler = Handler()
val runnable = Runnable {
btn.setEnabled(true)
}
updateHandler.postDelayed(runnable, 5000)
}
@SuppressLint("SuspiciousIndentation")
fun bind(item: DayListModel) = with(binding) {//Productitem - перпедаем данные
itemTemp = item itemTemp = item
//txtName.text = item.name //txtName.text = item.name
//txtCount.text = item.count //txtCount.text = item.count
//txtImage.text = item.image //txtImage.text = item.image
txtName.text = item.number txtName.text = item.number
txtDay.text = item.day txtDay.text = item.day
val category = item.category[0].toString()
if (category == "c"){
binding.imageSport.setImageResource(R.drawable.c_sport)
}
else if (category == "b"){
binding.imageSport.setImageResource(R.drawable.b_sport)
}
else if (category == "j"){
binding.imageSport.setImageResource(R.drawable.j_sport)
}
if(item.check.toInt() == 0){
binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
}
else if(item.check.toInt() == 1) {
binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#98EA88"))
}
else if(item.check.toInt() == 2){
binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#A68C78"))
} }
} }
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_day, parent, false)//Создаем(надуваем) list_item val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_day, parent, false)//Создаем(надуваем) list_item
return Holder(view, listener_zakaz)//Через Holder возврощаем view return Holder(view, listener_zakaz)//Через Holder возврощаем view
@ -55,19 +95,19 @@ class DayAdapter(val listener_zakaz: Listener) : ListAdapter<DayModel, DayAdapte
//Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает //Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает
class Comparator : DiffUtil.ItemCallback<DayModel>() { class Comparator : DiffUtil.ItemCallback<DayListModel>() {
override fun areItemsTheSame(oldItem: DayModel, newItem: DayModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет override fun areItemsTheSame(oldItem: DayListModel, newItem: DayListModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет
return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id) return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id)
} }
override fun areContentsTheSame(oldItem: DayModel, newItem: DayModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых override fun areContentsTheSame(oldItem: DayListModel, newItem: DayListModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых
return oldItem == newItem//Сравниваем полностью весь список новы и старый return oldItem == newItem//Сравниваем полностью весь список новы и старый
} }
} }
//Интерфейс нажатия на кнопку удалить товар из корзины //Интерфейс нажатия на кнопку удалить товар из корзины
interface Listener { interface Listener {
fun onClickDay(item: DayModel) fun onClickDay(item: DayListModel)
} }

View File

@ -0,0 +1,11 @@
package com.example.rehabilitation.model_adapter.Day
data class DayListModel(
val id: String,
val number: String,
val day: String,
val category: String,
val check:String,
//val categoryAlf: String,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Day
data class DayListOneModel(
val day: String,
)

View File

@ -1,4 +1,4 @@
package com.example.rehabilitation.dip.Day package com.example.rehabilitation.model_adapter.Day
data class DayModel( data class DayModel(
val id: String, val id: String,

View File

@ -0,0 +1,12 @@
package com.example.rehabilitation.model_adapter.Doctor
data class DoctorModel(
val id: String,
val name:String,
val surname:String,
val patronymic:String,
//val email:String,
val login:String,
val password:String,
)

View File

@ -0,0 +1,119 @@
package com.example.rehabilitation.model_adapter.Edit
import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.RcItemBinding
import com.example.rehabilitation.databinding.RcItemDayBinding
import com.example.rehabilitation.databinding.RcItemDayEditBinding
import java.time.LocalDate
class EditSportAdapter(val listener_zakaz: Listener,val visible_card: ListenerEdit) : ListAdapter<EditSportModel, EditSportAdapter.Holder>(
Comparator()
) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку
//В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку
class Holder(view: View, val listener_zakaz: Listener,val visible_card: ListenerEdit): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д.
//Для передачи данных
val binding = RcItemDayEditBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки
var itemTemp: EditSportModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия
//init - дает возможность внутри адаптера обращаться к элементам экрана
init {
itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка
itemTemp?.let { it1 -> listener_zakaz.onClickExceptionOrder(it1) }
}
binding.btnVisibleCardEdit.setOnClickListener {
itemTemp?.let { it2 -> visible_card.onClickEditCard(it2) }
}
}
//Функция bind для заполнения
@SuppressLint("SuspiciousIndentation")
fun bind(item: EditSportModel) = with(binding) {//Productitem - перпедаем данные
itemTemp = item
//txtName.text = item.name
//txtCount.text = item.count
//txtImage.text = item.image
txtName.text = item.id.toString()
txtDay.text = item.category
txtDescSport.text = item.desc
binding.CLMainPluss.visibility = if (item.expand) View.VISIBLE else View.GONE
binding.CLMainEdit.setOnClickListener{
if(item.expand == false){
binding.CLMainPluss.visibility = View.VISIBLE
item.expand = true
}else{
binding.CLMainPluss.visibility = View.GONE
item.expand = false
}
}
if(item.visible == 1){
binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
}
else{
binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#99ADBA"))
}
// if(item.check.toInt() == 0){
// binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#3AB0FF"))
// }
// else{
// binding.CardViewDay.setCardBackgroundColor(Color.parseColor("#33BC0E"))
// }
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_day_edit, parent, false)//Создаем(надуваем) list_item
return Holder(view, listener_zakaz,visible_card)//Через Holder возврощаем view
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val view = holder.bind(getItem(position))//Заполняем по позиции карточку
}
//Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает
class Comparator : DiffUtil.ItemCallback<EditSportModel>() {
override fun areItemsTheSame(oldItem: EditSportModel, newItem: EditSportModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет
return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id)
}
override fun areContentsTheSame(
oldItem: EditSportModel,
newItem: EditSportModel
): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых
return oldItem == newItem//Сравниваем полностью весь список новы и старый
}
}
//Открытие подробного описания спортивного упражнения
interface Listener {
fun onClickExceptionOrder(item: EditSportModel)
}
//Интерфейс нажатия на кнопку отключить карточку
interface ListenerEdit {
fun onClickEditCard(item: EditSportModel)
}
}

View File

@ -0,0 +1,13 @@
package com.example.rehabilitation.model_adapter.Edit
data class EditSportModel(
val id: Int,
val day: String,
val category: String,
val check:Int,
val visible:Int,
val desc:String,
val categoryImage:String,
var expand : Boolean = false
)

View File

@ -0,0 +1,33 @@
package com.example.rehabilitation.model_adapter.Edit.adapterFirebase
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.text.Html
import android.text.Spanned
import androidx.core.content.FileProvider
import androidx.core.net.toFile
import java.io.File
class Email {
fun getSendIntent(recipient: String,
subject: String,
text: String,
uri: Uri): Intent{
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "application/excel"
emailIntent.putExtra(Intent.EXTRA_STREAM, uri)
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient))
emailIntent.putExtra(Intent.EXTRA_TEXT, text)
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
emailIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
return emailIntent
}
}

View File

@ -0,0 +1,341 @@
package com.example.rehabilitation.model_adapter.Edit.adapterFirebase
import android.os.Environment
import android.util.Log
import com.example.rehabilitation.fileUri2
import com.example.rehabilitation.model_adapter.Progress.AfterListModel
import com.example.rehabilitation.model_adapter.Progress.BeforeListModel
import com.example.rehabilitation.uriFileEF
import org.apache.poi.ss.usermodel.BorderStyle
import org.apache.poi.ss.usermodel.CellStyle
import org.apache.poi.ss.usermodel.FillPatternType
import org.apache.poi.ss.usermodel.HorizontalAlignment
import org.apache.poi.ss.usermodel.IndexedColors
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.VerticalAlignment
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.util.CellRangeAddress
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
class ExcelFile( private val FIO: String, private val numDaysB: Int, private val numDaysA: Int, private val nameFile:String, private val BQDate: List<BeforeListModel>, private val AQDate: List<AfterListModel>) {
private lateinit var sheetAfter: Sheet
private lateinit var sheetBefore: Sheet
private lateinit var ourWorkbook: Workbook
private lateinit var cs: CellStyle
private lateinit var csRed: CellStyle
private lateinit var csGreen: CellStyle
private val filesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
init {
//Check whether it exists or not, and create one if it does not exist.
if (filesDir != null && !filesDir.exists()) {
filesDir.mkdirs()
}
ourWorkbook = createWorkbook()
Log.i("1", "1")
}
fun saveTable(){
val excelFile = File(filesDir, "/"+nameFile+".xlsx")
uriFileEF = excelFile
Log.i("excelFile","${excelFile}")
try {
val fileOut = FileOutputStream(excelFile)
fileUri2 = fileOut
Log.i("fileOut","${fileOut}")
ourWorkbook.write(fileOut)
fileOut.close()
Log.i("File", "Done")
} catch (e: FileNotFoundException) {
Log.e("File", e.message, e)
} catch (e: IOException) {
Log.e("File", e.message, e)
}
}
private fun createWorkbook(): Workbook {
Log.i("2", "2")
// Creating a workbook object from the XSSFWorkbook() class
ourWorkbook = XSSFWorkbook()
csRed = ourWorkbook.createCellStyle()
csRed.fillForegroundColor = IndexedColors.RED.index
csRed.fillPattern = FillPatternType.SOLID_FOREGROUND
csRed.verticalAlignment = VerticalAlignment.CENTER
csRed.alignment = HorizontalAlignment.CENTER
csRed.borderTop = BorderStyle.THIN;
csRed.borderBottom = BorderStyle.THIN;
csRed.borderLeft = BorderStyle.THIN;
csRed.borderRight = BorderStyle.THIN;
csRed.topBorderColor = IndexedColors.BLACK.index;
csRed.bottomBorderColor = IndexedColors.BLACK.index;
csRed.rightBorderColor = IndexedColors.BLACK.index;
csRed.leftBorderColor = IndexedColors.BLACK.index;
csGreen = ourWorkbook.createCellStyle()
csGreen.fillForegroundColor = IndexedColors.GREEN.index
csGreen.fillPattern = FillPatternType.SOLID_FOREGROUND
csGreen.verticalAlignment = VerticalAlignment.CENTER
csGreen.alignment = HorizontalAlignment.CENTER
csGreen.borderTop = BorderStyle.THIN;
csGreen.borderBottom = BorderStyle.THIN;
csGreen.borderLeft = BorderStyle.THIN;
csGreen.borderRight = BorderStyle.THIN;
csGreen.topBorderColor = IndexedColors.BLACK.index;
csGreen.bottomBorderColor = IndexedColors.BLACK.index;
csGreen.rightBorderColor = IndexedColors.BLACK.index;
csGreen.leftBorderColor = IndexedColors.BLACK.index;
cs = ourWorkbook.createCellStyle()
cs.verticalAlignment = VerticalAlignment.CENTER
cs.alignment = HorizontalAlignment.CENTER
cs.borderTop = BorderStyle.THIN;
cs.borderBottom = BorderStyle.THIN;
cs.borderLeft = BorderStyle.THIN;
cs.borderRight = BorderStyle.THIN;
cs.topBorderColor = IndexedColors.BLACK.index;
cs.bottomBorderColor = IndexedColors.BLACK.index;
cs.rightBorderColor = IndexedColors.BLACK.index;
cs.leftBorderColor = IndexedColors.BLACK.index;
sheetBefore = ourWorkbook.createSheet("Перед занятием")
sheetAfter = ourWorkbook.createSheet("После занятия")
addBeforeData()
addAfterData()
return ourWorkbook
}
private fun createCell(sheetRow: Row, columnIndex: Int, cellValue: String?, cellStyle: CellStyle?) {
Log.i("4", "4")
//create a cell at a passed in index
val ourCell = sheetRow.createCell(columnIndex)
//add the value to it
//a cell can be empty. That's why its nullable
ourCell?.setCellValue(cellValue)
if (cellStyle != null){
ourCell?.cellStyle = cellStyle
}
}
private fun addBeforeData() {
Log.i("31", "31")
Log.i("BQDate", "${BQDate[0].date.substring(5)}")
val row1 = sheetBefore.createRow(0)
val row2 = sheetBefore.createRow(1)
val row3 = sheetBefore.createRow(2)
val row4 = sheetBefore.createRow(3)
val row5 = sheetBefore.createRow(4)
val row6 = sheetBefore.createRow(5)
val row7 = sheetBefore.createRow(6)
val row8 = sheetBefore.createRow(7)
val row9 = sheetBefore.createRow(8)
val row10 = sheetBefore.createRow(9)
val row11 = sheetBefore.createRow(10)
val row12 = sheetBefore.createRow(11)
val row13 = sheetBefore.createRow(12)
sheetBefore.setColumnWidth(1, 25000)
sheetBefore.addMergedRegion(CellRangeAddress.valueOf("A1:${'B'+numDaysB}1"))
sheetBefore.addMergedRegion(CellRangeAddress.valueOf("B2:B3"))
sheetBefore.addMergedRegion(CellRangeAddress.valueOf("A2:A3"))
sheetBefore.addMergedRegion(CellRangeAddress.valueOf("C2:${'B'+numDaysB}2"))
createCell(row1, 0, "Анкета для контроля состояния пациента $FIO перед занятием", cs)
createCell(row2, 0, "№ п/п", cs)
createCell(row2, 1, "Вопрос", cs)
createCell(row2, 2, "День", cs)
for (i in 1..BQDate.count()){
Log.i("311", "311")
val date = BQDate[i-1].date.substring(5)
val day = "${date[3]}"+"${date[4]}"//День
val mount = "${date[0]}"+"${date[1]}"//Месяц
createCell(row3, 1+i, "${day}.${mount}", cs)
}
createCell(row4, 0, "1", cs)
createCell(row4, 1, "Есть ли у Вас фантомные боли?", cs)
createCell(row5, 0, "1.2", cs)
createCell(row5, 1, "Интенсивность фантомных болей?", cs)
createCell(row6, 0, "3", cs)
createCell(row6, 1, "Есть отек в области культи?", cs)
createCell(row7, 0, "4", cs)
createCell(row7, 1, "Есть ли покраснения в области культи?", cs)
createCell(row8, 0, "5", cs)
row8.height = 1000
createCell(row8, 1, "Есть ли покраснения в области культи?\n Есть ли локальное повышение температуры в области культи?", cs)
createCell(row9, 0, "6", cs)
createCell(row9, 1, "Есть ли выделения (кровь, сукровица) из области шва?", cs)
createCell(row10, 0, "7", cs)
createCell(row10, 1, "Есть ли повышение температуры (общее) выше 37,5?", cs)
createCell(row11, 0, "8", cs)
createCell(row11, 1, "Было ли ухудшение состояния после предыдущего занятия?", cs)
createCell(row12, 0, "9", cs)
createCell(row12, 1, "Удалось ли полностью восстановиться после предыдущего занятия?", cs)
createCell(row13, 0, "10", cs)
createCell(row13, 1, "Были ухудшения самочувствия?", cs)
}
private fun addAfterData() {
Log.i("32", "32")
val row1 = sheetAfter.createRow(0)
val row2 = sheetAfter.createRow(1)
val row3 = sheetAfter.createRow(2)
val row4 = sheetAfter.createRow(3)
val row5 = sheetAfter.createRow(4)
val row6 = sheetAfter.createRow(5)
val row7 = sheetAfter.createRow(6)
val row8 = sheetAfter.createRow(7)
val row9 = sheetAfter.createRow(8)
val row10 = sheetAfter.createRow(9)
val row11 = sheetAfter.createRow(10)
val row12 = sheetAfter.createRow(11)
val row13 = sheetAfter.createRow(12)
val row14 = sheetAfter.createRow(13)
val row15 = sheetAfter.createRow(14)
sheetAfter.setColumnWidth(1, 25000)
sheetAfter.addMergedRegion(CellRangeAddress.valueOf("A1:${'B'+numDaysA}1"))
sheetAfter.addMergedRegion(CellRangeAddress.valueOf("B2:B3"))
sheetAfter.addMergedRegion(CellRangeAddress.valueOf("A2:A3"))
sheetAfter.addMergedRegion(CellRangeAddress.valueOf("C2:${'B'+numDaysA}2"))
createCell(row1, 0, "Анкета для контроля состояния пациента $FIO после занятия", cs)
createCell(row2, 0, "№ п/п", cs)
createCell(row2, 1, "Вопрос", cs)
createCell(row2, 2, "День", cs)
for (i in 1..AQDate.count()){
val date = AQDate[i-1].date.substring(5)
val day = "${date[3]}"+"${date[4]}"//День
val mount = "${date[0]}"+"${date[1]}"//Месяц
createCell(row3, 1+(i), "${day}.${mount}", cs)
}
createCell(row4, 0, "1", cs)
createCell(row4, 1, "Интенсивность фантомных болей?", cs)
createCell(row5, 0, "2", cs)
createCell(row5, 1, "Было ли усиление болевого синдрома во время занятий? ", cs)
createCell(row6, 0, "3", cs)
row6.height = 1000
createCell(row6, 1, "При прекращении упражнения, которое вызвало усиление болевого синдрома,\n боль купируется (или возвращается к уровню до занятия) в течение 2 минут? ", cs)
createCell(row7, 0, "4", cs)
createCell(row7, 1, "Интенсивность болевого синдрома до занятия и после одинаковая? ", cs)
createCell(row8, 0, "5", cs)
createCell(row8, 1, "Есть отек в области культи? ", cs)
createCell(row9, 0, "6", cs)
createCell(row9, 1, "По сравнению с состояние перед занятием увеличился ли отек культи?", cs)
createCell(row10, 0, "7", cs)
createCell(row10, 1, "Есть ли покраснения в области культи? ", cs)
createCell(row11, 0, "8", cs)
createCell(row11, 1, "Есть ли локальное повышение температуры в области культи?", cs)
createCell(row12, 0, "9", cs)
createCell(row12, 1, "Есть ли выделения (кровь, сукровица) из области шва?", cs)
createCell(row13, 0, "10", cs)
createCell(row13, 1, "Выделения из области шва усилились/изменили характер?", cs)
createCell(row14, 0, "11", cs)
createCell(row14, 1, "Есть ли общее ощущение слабости, чрезмерной усталости, «разбитости»?", cs)
createCell(row15, 0, "12", cs)
createCell(row15, 1, "Все ли упражнения удалось выполнить?", cs)
}
fun addBeforeDay(day: Int, question: Int, data: Int){
if ((day > numDaysB) or (question > 10)){
throw ArrayIndexOutOfBoundsException("Выход за пределы таблицы")
}
val row = sheetBefore.getRow(question+2)
if (question == 2){
if (data > 5){
createCell(row, day+1, data.toString(), csRed)
}
else {
createCell(row, day+1, data.toString(), csGreen)
}
}
else{
if (question == 9){
when(data){
0 -> createCell(row, day+1, "Нет", csRed)
else -> createCell(row, day+1, "Да", csGreen)
}
}
else {
when(data){
0 -> createCell(row, day+1, "Нет", csGreen)
else -> createCell(row, day+1, "Да", csRed)
}
}
}
}
fun addAfterDay(day: Int, question: Int, data: Int){
if ((day > numDaysA) or (question > 12)){
throw ArrayIndexOutOfBoundsException("Выход за пределы таблицы")
}
val row = sheetAfter.getRow(question+2)
if (question == 1){
if (data > 5){
createCell(row, day+1, data.toString(), csRed)
}
else {
createCell(row, day+1, data.toString(), csGreen)
}
}
else{
if (question in listOf(3, 4, 12)){
when(data){
0 -> createCell(row, day+1, "Нет", csRed)
else -> createCell(row, day+1, "Да", csGreen)
}
}
else {
when(data){
0 -> createCell(row, day+1, "Нет", csGreen)
else -> createCell(row, day+1, "Да", csRed)
}
}
}
}
}

View File

@ -0,0 +1,83 @@
package com.example.rehabilitation.model_adapter.Edit.adapterFirebase
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.RemoteViews
import androidx.core.app.NotificationCompat
//import com.google.firebase.messaging.FirebaseMessagingService
//import com.google.firebase.messaging.RemoteMessage
const val channel_id = "channel_id"
const val channel_name = "user"
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
//class MyFirebaseMessagingService:FirebaseMessagingService() {
class MyFirebaseMessagingService {
/*
//Вывод уведомления
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if(remoteMessage.notification != null){
try {
generateNotification(
remoteMessage.notification!!.title!!,
remoteMessage.notification!!.body!!
)
}
catch (e: Exception){
}
}
}
fun generateNotification(title:String, message:String){
val intent = Intent(this, MainActivity::class.java)
//Вывод уведомления поверх всех экранов
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
//Удаляем уведомление по нажатию на него 1 раз
val pendingIntent = PendingIntent.getActivity(this, 0,intent,PendingIntent.FLAG_ONE_SHOT)
//
var builder=NotificationCompat.Builder(applicationContext, channel_id)
.setSmallIcon(R.drawable.cart_24)//Изображение
.setAutoCancel(true)
.setVibrate(longArrayOf(1000,1000,1000,1000))//Вибрации 1 секунда вибрации 1 секунда бе и повтор
.setContentIntent(pendingIntent)//Создалии строитель
builder = builder.setContent(getRemoteView(title, message))
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//Если версия выше или равна oreo
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
val notificationChannel = NotificationChannel(channel_id, channel_name,NotificationManager.IMPORTANCE_HIGH)
notificationManager.createNotificationChannel(notificationChannel)
}
//Отправляем уведомление
notificationManager.notify(0,builder.build())
}
private fun getRemoteView(title: String, message: String): RemoteViews? {
//Разметка
val remoteView = RemoteViews("com.example.get_post_zaprose.Chat.firebase",R.layout.push_notification)
//Присваиваем значения
remoteView.setTextViewText(R.id.txtTitle,title)
remoteView.setTextViewText(R.id.txtTitle2,message)
remoteView.setImageViewResource(R.id.imLogo,R.drawable.cart_24)
return remoteView
}*/
}

View File

@ -0,0 +1,7 @@
package com.example.rehabilitation.model_adapter.Edit.adapterFirebase
//Класс с помошью которого мы будем хранить информацию на Firebase
data class ReportPatient(
val name:String? = null,//? - так как может быть равен null
val message:String? = null,
)

View File

@ -0,0 +1,11 @@
package com.example.rehabilitation.model_adapter.Edit.adapterFirebase
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import java.io.File
import java.io.FileOutputStream
class sample {
}

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Image.Category
data class CountCategoryModel(
val count: String,
)

View File

@ -0,0 +1,8 @@
package com.example.rehabilitation.model_adapter.Image.Category
data class CountNameCategoryArticleModel(
val count: String,
val name: String,
val article: String,
)

View File

@ -0,0 +1,7 @@
package com.example.rehabilitation.model_adapter.Image.Category
data class CountNameCategoryModel(
val count: String,
val name: String,
)

View File

@ -1,5 +1,7 @@
package com.example.rehabilitation.dip.Image package com.example.rehabilitation.model_adapter.Image
import android.annotation.SuppressLint
import android.content.Context
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
@ -8,17 +10,15 @@ import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.ImageSportCardsBinding import com.example.rehabilitation.databinding.ImageSportCardsBinding
import com.example.rehabilitation.databinding.RcItemDayBinding
import java.time.LocalDate
class ImageSportAdapter() : ListAdapter<ImageSportModel, ImageSportAdapter.Holder>( class ImageSportAdapter(val contextF:Context) : ListAdapter<ImageSportModel, ImageSportAdapter.Holder>(
Comparator() Comparator()
) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку ) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку
//В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку //В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку
class Holder(view: View): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д. class Holder(view: View,val contextF:Context): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д.
//Для передачи данных //Для передачи данных
val binding = ImageSportCardsBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки val binding = ImageSportCardsBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки
@ -34,16 +34,18 @@ class ImageSportAdapter() : ListAdapter<ImageSportModel, ImageSportAdapter.Holde
} }
//Функция bind для заполнения //Функция bind для заполнения
@SuppressLint("DiscouragedApi")
fun bind(item: ImageSportModel) = with(binding) {//Productitem - перпедаем данные fun bind(item: ImageSportModel) = with(binding) {//Productitem - перпедаем данные
itemTemp = item itemTemp = item
imageSport.setImageResource(item.imageName.toInt()) val image = contextF.resources.getIdentifier("${item.imageName}", "drawable", contextF.packageName)
imageSport.setImageResource(image)
} }
} }
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.image_sport_cards, parent, false)//Создаем(надуваем) list_item val view = LayoutInflater.from(parent.context).inflate(R.layout.image_sport_cards, parent, false)//Создаем(надуваем) list_item
return Holder(view)//Через Holder возврощаем view return Holder(view, contextF)//Через Holder возврощаем view
} }
override fun onBindViewHolder(holder: Holder, position: Int) { override fun onBindViewHolder(holder: Holder, position: Int) {

View File

@ -1,4 +1,4 @@
package com.example.rehabilitation.dip.Image package com.example.rehabilitation.model_adapter.Image
data class ImageSportModel( data class ImageSportModel(
val id: String, val id: String,

View File

@ -0,0 +1,97 @@
package com.example.sqlitework.dip
import android.app.Application
import androidx.lifecycle.*
import com.example.rehabilitation.model_adapter.Image.Category.CountCategoryModel
import com.example.rehabilitation.model_adapter.Day.DayListModel
import com.example.rehabilitation.model_adapter.Day.DayListOneModel
import com.example.rehabilitation.model_adapter.Day.DayModel
import com.example.rehabilitation.model_adapter.Doctor.DoctorModel
import com.example.rehabilitation.model_adapter.Edit.EditSportModel
import com.example.rehabilitation.model_adapter.Image.Category.CountNameCategoryModel
import com.example.rehabilitation.model_adapter.Image.ImageSportModel
import com.example.rehabilitation.model_adapter.Month.MonthModel
import com.example.rehabilitation.model_adapter.Patient.PatientModel
import com.example.rehabilitation.model_adapter.Progress.AfterListModel
import com.example.rehabilitation.model_adapter.Progress.BeforeListModel
import com.example.rehabilitation.model_adapter.Progress.ProgressModel
import com.example.rehabilitation.model_adapter.Questionnair.AfterModel
import com.example.rehabilitation.model_adapter.Questionnair.BeforeModel
import com.example.rehabilitation.model_adapter.Questionnair.CountSportModel
import com.example.rehabilitation.model_adapter.Questionnair.CountSportPlusModel
import com.example.rehabilitation.model_adapter.Questionnair.NameSportModel
import com.example.rehabilitation.model_adapter.SportCategory.SportCategoryModel
import com.example.rehabilitation.model_adapter.modelCount.CountDayModel
import com.example.rehabilitation.model_adapter.modelCount.CountMonthModel
//Тут будут обновлятся данные, следим за списками если что-то обновилось, то уведомлякм и потом ProductAdapter обновит
class MainViewModel(application: Application) :AndroidViewModel(application){
//Объявления
val liveListCurrent = MutableLiveData<MonthModel>()//Сюда передается новая информация на один день(для слайдера)
val liveListList= MutableLiveData<List<MonthModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveDayCurrent = MutableLiveData<DayModel>()//Сюда передается новая информация на один день(для слайдера)
val liveDayList= MutableLiveData<List<DayListModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveDayListProgres= MutableLiveData<List<DayListModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveDayListProgres2= MutableLiveData<List<DayListModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveImageCurrent = MutableLiveData<ImageSportModel>()//Сюда передается новая информация на один день(для слайдера)
val liveImageList= MutableLiveData<List<ImageSportModel>>()//Сюда передается новая информация на один день(для все продукции - всего списка)
val liveCountCategoryCurrent = MutableLiveData<CountCategoryModel>()//Сюда передается новая информация на один день(для слайдера)
val liveCountNameCategoryCurrent = MutableLiveData<CountNameCategoryModel>()//Сюда передается новая информация на один день(для слайдера)
val liveAuthPatientCurrent = MutableLiveData<PatientModel>()//Сюда передается новая информация на один день(для слайдера)
val liveAuthDoctorCurrent = MutableLiveData<DoctorModel>()//Сюда передается новая информация на один день(для слайдера)
//Количество дней прошедших
val liveCountMonthCurrent = MutableLiveData<CountMonthModel>()//Сюда передается новая информация на один день(для слайдера)
//Количество пройденых тренировок
val liveCountDayCurrent = MutableLiveData<CountDayModel>()//Сюда передается новая информация на один день(для слайдера)
val liveCountDaySceduleCurrent = MutableLiveData<CountDayModel>()//Сюда передается новая информация на один день(для слайдера)
//Информация пациента
val liveSettingPatientCurrent = MutableLiveData<PatientModel>()
val liveLookPatientCurrent = MutableLiveData<PatientModel>()
val liveSettingDoctorCurrent = MutableLiveData<DoctorModel>()
//Информация для анкетирования
val liveAfterCurrent = MutableLiveData<AfterModel>()
val liveBeforeCurrent = MutableLiveData<BeforeModel>()
val liveCountSportCurrent = MutableLiveData<CountSportModel>()
val liveCountSportPlusCurrent = MutableLiveData<CountSportPlusModel>()
val liveNameSportCurrent = MutableLiveData<NameSportModel>()
val liveCountDaySportandPlusCurrent = MutableLiveData<CountDayModel>()
//Список для редактирвоания
val liveEditSportCurrent = MutableLiveData<EditSportModel>()
val liveEditSportList= MutableLiveData<List<EditSportModel>>()
//Список для редактирвоания
val liveListDaySportOneCurrent = MutableLiveData<DayListOneModel>()
//АНКЕТИРОВАНИЕ
//Список для редактирвоания
val liveListProgresBeforeList = MutableLiveData<List<BeforeListModel>>()
val liveListProgresAfterList = MutableLiveData<List<AfterListModel>>()
//ПРОГРЕСС
val liveProgressAllList = MutableLiveData<List<ProgressModel>>()
val liveProgressCheckList = MutableLiveData<List<ProgressModel>>()
//Количество упражнений
val liveCountSportCategoryCurrent = MutableLiveData<SportCategoryModel>()
val liveSportCategoryAllArticleList = MutableLiveData<List<SportCategoryModel>>()
}

View File

@ -1,13 +1,18 @@
package com.example.rehabilitation.dip.Month package com.example.rehabilitation.model_adapter.Month
import android.annotation.SuppressLint
import android.graphics.Color
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.CursDayNull
import com.example.rehabilitation.R import com.example.rehabilitation.R
import com.example.rehabilitation.SportCursDay
import com.example.rehabilitation.databinding.RcItemBinding import com.example.rehabilitation.databinding.RcItemBinding
import java.time.LocalDate
class MonthAdapter(val listener_zakaz: Listener) : ListAdapter<MonthModel, MonthAdapter.Holder>( class MonthAdapter(val listener_zakaz: Listener) : ListAdapter<MonthModel, MonthAdapter.Holder>(
@ -32,10 +37,23 @@ class MonthAdapter(val listener_zakaz: Listener) : ListAdapter<MonthModel, Month
} }
//Функция bind для заполнения //Функция bind для заполнения
@SuppressLint("SuspiciousIndentation")
fun bind(item: MonthModel) = with(binding) {//Productitem - перпедаем данные fun bind(item: MonthModel) = with(binding) {//Productitem - перпедаем данные
var data = SportCursDay
var dataLocalDate = LocalDate.now().toString()
itemTemp = item itemTemp = item
txtDay.text = item.day txtDay.text = item.day
txtTitle.text = item.date txtTitle.text = "День "+item.date
if(data.toString() == item.date || item.day == CursDayNull){
binding.cardViewMonth.setCardBackgroundColor(Color.parseColor("#A7DCFF"))
}
else if(dataLocalDate < item.day || item.day == "" && item.day !=CursDayNull ){
binding.cardViewMonth.setCardBackgroundColor(Color.parseColor("#5DA6E1"))
}
else{
binding.cardViewMonth.setCardBackgroundColor(Color.parseColor("#98EA88"))
}
} }
} }

View File

@ -1,4 +1,4 @@
package com.example.rehabilitation.dip.Month package com.example.rehabilitation.model_adapter.Month
data class MonthModel( data class MonthModel(
val id: String, val id: String,

View File

@ -0,0 +1,14 @@
package com.example.rehabilitation.model_adapter.Patient
data class PatientModel(
val id: String,
val name:String,
val surname:String,
val patronymic:String,
val diagnosis:String,
val number_of_courses:String,
//val email:String,
val login:String,
val password:String,
)

View File

@ -0,0 +1,19 @@
package com.example.rehabilitation.model_adapter.Progress
data class AfterListModel(
val id: Int,
val one: String,
val two: String,
val thee:String,
val four:String,
val five:String,
val six:String,
val seven:String,
val eight:String,
val nine:String,
val ten:String,
val eleven:String,
val twelve:String,
val date:String,
)

View File

@ -0,0 +1,18 @@
package com.example.rehabilitation.model_adapter.Progress
data class BeforeListModel(
val id: Int,
val one: String,
val two: String,
val thee:String,
val four:String,
val five:String,
val six:String,
val seven:String,
val eight:String,
val nine:String,
val date:String,
)

View File

@ -0,0 +1,102 @@
package com.example.rehabilitation.model_adapter.Progress
import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.rehabilitation.R
import com.example.rehabilitation.databinding.RcItemDayBinding
import com.example.rehabilitation.databinding.RcItemProgressBinding
class ProgressAdapter(val listener_zakaz: Listener) : ListAdapter<ProgressModel, ProgressAdapter.Holder>(
Comparator()
) {//Productitem - по этой форме будем заполнять.//ProductAdapter.holder - это создаваемый holder который хранит логику как нужно заполнять карточку
//В holder создаетс код с помошью которого мы будем заполнять и сохронять разметку
class Holder(view: View, val listener_zakaz: Listener): RecyclerView.ViewHolder(view) {//Класс который будет хранить сссылки на элементы, и отвечает за один элемент за 1 раз, то есть сначсало нулевой элемент заполнит, потом первый, потом второй и т.д.
//Для передачи данных
val binding = RcItemProgressBinding.bind(view)//view - здесь храянтся элементы и мы их bind заполним в ListItemBinding//ListItemBinding - это клласс даннйо разметки(карточки) которую мы будем заполнять, а нужна дання переменная(binding), чтобы мжно было при заполнение обращатся к элементам карточки
var itemTemp: ProgressModel? = null//Глобальная переменная для нашего item, чтобы можно было передать данные для нажатия
//init - дает возможность внутри адаптера обращаться к элементам экрана
init {
itemView.setOnClickListener {//Нажатие на ячейку//itemView - это весь элемент карточки из списка
itemView.setEnabled(false)
timerButtonDoubleButton(itemView)
itemTemp?.let { it1 -> listener_zakaz.onClickDay(it1) }
}
}
//Функция bind для заполнения
//ЗАдержка нажатия на кнопку
private fun timerButtonDoubleButton(btn: View){
val updateHandler = Handler()
val runnable = Runnable {
btn.setEnabled(true)
}
updateHandler.postDelayed(runnable, 5000)
}
@SuppressLint("SuspiciousIndentation")
fun bind(item: ProgressModel) = with(binding) {//Productitem - перпедаем данные
itemTemp = item
txtDate.text = item.id+". " + item.date + ": "
txtProgress.text = item.CountCheckTrue.toString()+"/"+item.countAll.toString()
if(item.CountCheckTrue == 0) {
CardViewDay.setCardBackgroundColor(Color.parseColor("#1993FF"))
}
else{
CardViewDay.setCardBackgroundColor(Color.parseColor("#98EA88"))
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_item_progress, parent, false)//Создаем(надуваем) list_item
return Holder(view, listener_zakaz)//Через Holder возврощаем view
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val view = holder.bind(getItem(position))//Заполняем по позиции карточку
}
//Comparator - сравнивает старый список и новый и если что-то изменилось, то работает с конкретным изменением списке, а не весь список переписывает
class Comparator : DiffUtil.ItemCallback<ProgressModel>() {
override fun areItemsTheSame(oldItem: ProgressModel, newItem: ProgressModel): Boolean {//Тут лучше всего сравнивать по id//oldItem - элементы старого списка, newItem - элементы нового списка//Возврощает Boolean, тоесть есть изменения или нет
return oldItem.id == newItem.id//Сравниваем полностью весь список новы и старый, по очередно по одной карточке и по элементно, то есть нулевой элемент, первый, второй и т.д.. Но лучше сравнивать по id списки, а не просто весь список, так как это эфективнее, так как id уникальный(oldItem.id == newItem.id)
}
override fun areContentsTheSame(oldItem: ProgressModel, newItem: ProgressModel): Boolean {//Утут нужно сравнивать весь спсок старых элементов и новых
return oldItem == newItem//Сравниваем полностью весь список новы и старый
}
}
//Интерфейс нажатия на кнопку удалить товар из корзины
interface Listener {
fun onClickDay(item: ProgressModel)
}
}

View File

@ -0,0 +1,11 @@
package com.example.rehabilitation.model_adapter.Progress
data class ProgressModel(
val id: String,
val countAll: Int,
var CountCheckTrue: Int,
val category: String,
val date:String,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Questionnair
data class AfterModel(
val date: String,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Questionnair
data class BeforeModel(
val date: String,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Questionnair
data class CountSportModel(
val count: Int,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Questionnair
data class CountSportPlusModel(
val count: Int,
)

View File

@ -0,0 +1,6 @@
package com.example.rehabilitation.model_adapter.Questionnair
data class NameSportModel(
val name: String,
)

View File

@ -0,0 +1,13 @@
package com.example.rehabilitation.model_adapter.SportCategory
data class SportCategoryModel(
val id: String,
val name: String,
val desc:String,
val count: String,
val image: String,
val category: String,
val article:String,
val check:Int,
)

View File

@ -0,0 +1,7 @@
package com.example.rehabilitation.model_adapter.modelCount
data class CountDayModel(
val countDown: Int,
val countAll: Int,
)

Some files were not shown because too many files have changed in this diff Show More