Descargar PDF en pruebas

This commit is contained in:
sebastiancc27 2024-05-09 22:27:17 -06:00
parent 9c7d539484
commit b49828a221
12 changed files with 354 additions and 23 deletions

View File

@ -3,20 +3,7 @@
<component name="deploymentTargetDropDown"> <component name="deploymentTargetDropDown">
<value> <value>
<entry key="app"> <entry key="app">
<State> <State />
<runningDeviceTargetSelectedWithDropDown>
<Target>
<type value="RUNNING_DEVICE_TARGET" />
<deviceKey>
<Key>
<type value="SERIAL_NUMBER" />
<value value="ZX1D9224Q7" />
</Key>
</deviceKey>
</Target>
</runningDeviceTargetSelectedWithDropDown>
<timeTargetWasSelectedWithDropDown value="2024-05-08T23:05:47.315686700Z" />
</State>
</entry> </entry>
</value> </value>
</component> </component>

View File

@ -51,6 +51,7 @@ 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("androidx.navigation:navigation-fragment-ktx:2.6.0") implementation("androidx.navigation:navigation-fragment-ktx:2.6.0")
implementation("com.dmitryborodin:pdfview-android:1.1.0")
implementation("androidx.navigation:navigation-ui-ktx:2.6.0") implementation("androidx.navigation:navigation-ui-ktx:2.6.0")
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")

View File

@ -15,6 +15,9 @@
android:supportsRtl="true" android:supportsRtl="true"
android:theme="@style/Theme.MedicalHealth" android:theme="@style/Theme.MedicalHealth"
tools:targetApi="31"> tools:targetApi="31">
<activity
android:name=".PacientePrincipalActivity"
android:exported="false" />
<activity <activity
android:name=".EliminarRecetaActivity" android:name=".EliminarRecetaActivity"
android:exported="false" /> android:exported="false" />

View File

@ -0,0 +1,7 @@
package Adapters
import Data.Receta
interface CellClickListener {
fun onCellClickListener(position : Int)
}

View File

@ -7,6 +7,7 @@ import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteOpenHelper
import Data.Doctor import Data.Doctor
import Data.Paciente import Data.Paciente
import android.database.Cursor
class DoctorDataBaseHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME,null, class DoctorDataBaseHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME,null,
DATABASE_VERSION DATABASE_VERSION
@ -114,15 +115,42 @@ class DoctorDataBaseHelper (context: Context) : SQLiteOpenHelper(context, DATABA
val dropQuery="DROP TABLE IF EXISTS $TABLE_NAME" val dropQuery="DROP TABLE IF EXISTS $TABLE_NAME"
db?.execSQL(dropQuery) db?.execSQL(dropQuery)
} }
fun validarDatos(cedula :String , contrasena : String): Boolean{
fun validarDatos(usuario :String , contrasena : String): Boolean{
val db = readableDatabase val db = readableDatabase
val validarQuery = "SELECT * FROM $TABLE_NAME WHERE $COLUMN_CEDULA = '$cedula' AND $COLUMN_CONTRASENA = '$contrasena'" val validarQuery = "SELECT $COLUMN_CEDULA,$COLUMN_CONTRASENA FROM $TABLE_NAME, $TABLE_PACIENTES WHERE $COLUMN_CEDULA = '$usuario' AND $COLUMN_CONTRASENA = '$contrasena' "
val cursor = db.rawQuery(validarQuery, null) val cursor = db.rawQuery(validarQuery, null)
val isValid = cursor.count > 0 val isValid = cursor.count > 0
cursor.close() cursor.close()
return isValid return isValid
} }
@SuppressLint("Range")
fun seleccionarDoctores(): List<Doctor>{
val doctores= mutableListOf<Doctor>()
val db= readableDatabase
val query="SELECT * FROM $TABLE_NAME "
val cursor=db.query(TABLE_NAME,null,null,null,null,null,null)
while (cursor.moveToNext()){
val cedula=cursor.getString(cursor.getColumnIndex(COLUMN_CEDULA))
val nombre=cursor.getString(cursor.getColumnIndex(COLUMN_NOMBRE))
val apellido=cursor.getString(cursor.getColumnIndex(COLUMN_APELLIDO))
val telefono = cursor.getString(cursor.getColumnIndex(COLUMN_TELEFONO))
val consultorio=cursor.getInt(cursor.getColumnIndex(COLUMN_CONSULTORIO))
val contrasena=cursor.getString(cursor.getColumnIndex(COLUMN_CONTRASENA))
val doctor = Doctor(cedula,nombre,apellido,telefono,consultorio)
doctores.add(doctor)
}
return doctores
}
fun validarDatosPaciente(usuario : String, contrasena: String): Boolean{
val db = readableDatabase
val validarQuery = "SELECT $COLUMN_ID_PACIENTE,$COLUMN_NOMBRE_PACIENTE FROM $TABLE_PACIENTES WHERE $COLUMN_ID_PACIENTE = '$usuario' AND $COLUMN_NOMBRE_PACIENTE = '$contrasena' "
val cursor = db.rawQuery(validarQuery, null)
val isValid = cursor.count > 0
cursor.close()
return isValid
}
fun edadPaciente(nombrePaciente : String) : Int{ fun edadPaciente(nombrePaciente : String) : Int{
val db=readableDatabase val db=readableDatabase
var edadPaciente =0 var edadPaciente =0

View File

@ -4,6 +4,7 @@ import Data.Receta
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.content.ContentValues import android.content.ContentValues
import android.content.Context import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper import android.database.sqlite.SQLiteOpenHelper
@ -53,6 +54,8 @@ class RecetaDataBaseHelper(context: Context) : SQLiteOpenHelper(context, DATABAE
val recetas = mutableListOf<Receta>() val recetas = mutableListOf<Receta>()
val db = readableDatabase val db = readableDatabase
val cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null) val cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
//val cursor : Cursor =db.query(TABLE_NAME,null,null,null,null,null,null)
if(cursor!=null){
while (cursor.moveToNext()) { while (cursor.moveToNext()) {
val nombrePaciente = cursor.getString(cursor.getColumnIndex(COLUMN_NOMBRE_PACIENTE)) val nombrePaciente = cursor.getString(cursor.getColumnIndex(COLUMN_NOMBRE_PACIENTE))
val edadPaciente = cursor.getInt(cursor.getColumnIndex(COLUMN_EDAD_PACIENTE)) val edadPaciente = cursor.getInt(cursor.getColumnIndex(COLUMN_EDAD_PACIENTE))
@ -65,6 +68,27 @@ class RecetaDataBaseHelper(context: Context) : SQLiteOpenHelper(context, DATABAE
recetas.add(receta) recetas.add(receta)
} }
cursor.close() cursor.close()
}
db.close()
return recetas
}
@SuppressLint("Range")
fun obtenerRecetasPaciente(nombrePaciente : String): List<Receta>{
val recetas = mutableListOf<Receta>()
val db = readableDatabase
val cursor = db.rawQuery("SELECT $COLUMN_NOMBRE_PACIENTE,$COLUMN_MEDICAMENTO, $COLUMN_FECHA FROM $TABLE_NAME WHERE $COLUMN_NOMBRE_PACIENTE = '$nombrePaciente'", null)
while (cursor.moveToNext()) {
val nombrePaciente = cursor.getString(cursor.getColumnIndex(COLUMN_NOMBRE_PACIENTE))
//val edadPaciente = cursor.getInt(cursor.getColumnIndex(COLUMN_EDAD_PACIENTE))
//val pesoPaciente = cursor.getDouble(cursor.getColumnIndex(COLUMN_PESO_PACIENTE))
val medicamento = cursor.getString(cursor.getColumnIndex(COLUMN_MEDICAMENTO))
val fecha = cursor.getString(cursor.getColumnIndex(COLUMN_FECHA))
//val dosis = cursor.getString(cursor.getColumnIndex(COLUMN_DOSIS_PACIENTE))
//val duracion = cursor.getString(cursor.getColumnIndex(DURACION_MEDICAMENTO))
val receta = Receta(nombrePaciente, 0, 0.0, medicamento, fecha, "dosis", "duracion")
recetas.add(receta)
}
cursor.close()
return recetas return recetas
} }
@ -73,4 +97,9 @@ class RecetaDataBaseHelper(context: Context) : SQLiteOpenHelper(context, DATABAE
db.delete(TABLE_NAME, "$COLUMN_NOMBRE_PACIENTE = ? AND $COLUMN_FECHA = ?", arrayOf(receta.NombrePaciente, receta.fecha)) db.delete(TABLE_NAME, "$COLUMN_NOMBRE_PACIENTE = ? AND $COLUMN_FECHA = ?", arrayOf(receta.NombrePaciente, receta.fecha))
db.close() db.close()
} }
fun getCursor() : Cursor?{
val db = writableDatabase
val cursor = db.rawQuery("SELECT * FROM $TABLE_NAME", null)
return cursor
}
} }

View File

@ -0,0 +1,46 @@
package Adapters
import Data.Receta
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView.OnItemClickListener
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.terratenientes.medicalhealth.R
class RecetaViewAdapter(private var notes : List<Receta>, context: Context,val cellClickListener: CellClickListener) :
RecyclerView.Adapter<RecetaViewAdapter.NoteViewHolder>() {
class NoteViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val tituloReceta : TextView = itemView.findViewById(R.id.tv_titulo_receta)
val fechaReceta : TextView = itemView.findViewById(R.id.tv_fecha_receta)
val btnDescargar : Button = itemView.findViewById(R.id.btn_descargar_receta)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.rc_receta_item, parent, false)
return NoteViewHolder(view)
}
override fun getItemCount(): Int {
return notes.size
}
override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
val note = notes[position]
holder.tituloReceta.text = note.nombreMedicamento
holder.fechaReceta.text = note.fecha
holder.btnDescargar.setOnClickListener{
cellClickListener.onCellClickListener(position)
}
}
fun refreshData( newNotes : List<Receta>){
this.notes=newNotes
notifyDataSetChanged()
}
}

View File

@ -1,3 +1,3 @@
package Data package Data
data class Receta(val NombrePaciente : String, val edadPaciente : Int, val pesoPaciente: Double, val nombreMedicamento : String, val fecha : String, val dosis : String, val duracion :String) data class Receta(var NombrePaciente : String, var edadPaciente : Int, var pesoPaciente: Double, var nombreMedicamento : String, var fecha : String, var dosis : String, var duracion :String)

View File

@ -19,11 +19,19 @@ class MainActivity : AppCompatActivity() {
setContentView(view) setContentView(view)
db = DoctorDataBaseHelper(this@MainActivity) db = DoctorDataBaseHelper(this@MainActivity)
//db.createTable()
binding.btnIniciarSesion.setOnClickListener { binding.btnIniciarSesion.setOnClickListener {
var res=db.validarDatos(binding.tvUsuario.text.toString(),binding.tvContrasena.text.toString()) var res=db.validarDatos(binding.tvUsuario.text.toString(),binding.tvContrasena.text.toString())
var resPaciente = db.validarDatosPaciente(binding.tvUsuario.text.toString(), binding.tvContrasena.text.toString())
if(res==true){ if(res==true){
Toast.makeText(this@MainActivity,"VALIDADO",Toast.LENGTH_LONG).show() Toast.makeText(this@MainActivity,"VALIDADO",Toast.LENGTH_LONG).show()
val intent = Intent(this@MainActivity, PrincipalActivity::class.java) val intent = Intent(this@MainActivity, PrincipalActivity::class.java)
//intent.putExtra("IDPaciente",binding.tvUsuario.text.toString())
startActivity(intent)
}else if(resPaciente==true){
Toast.makeText(this@MainActivity,"VALIDADO",Toast.LENGTH_LONG).show()
val intent = Intent(this@MainActivity, PacientePrincipalActivity::class.java)
intent.putExtra("IDPaciente",binding.tvContrasena.text.toString())
startActivity(intent) startActivity(intent)
}else{ }else{
Toast.makeText(this@MainActivity," NO VALIDADO",Toast.LENGTH_LONG).show() Toast.makeText(this@MainActivity," NO VALIDADO",Toast.LENGTH_LONG).show()

View File

@ -0,0 +1,132 @@
package com.terratenientes.medicalhealth
import Adapters.CellClickListener
import Adapters.RecetaDataBaseHelper
import Adapters.RecetaViewAdapter
import Data.Receta
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Typeface
import android.graphics.pdf.PdfDocument
import android.os.Bundle
import android.os.Environment
import android.text.TextPaint
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.terratenientes.medicalhealth.databinding.ActivityPacientePrincipalBinding
import java.io.File
import java.io.FileOutputStream
class PacientePrincipalActivity : AppCompatActivity(), CellClickListener {
private lateinit var binding: ActivityPacientePrincipalBinding
private var idPaciente : String =""
private lateinit var db: RecetaDataBaseHelper
private lateinit var recycleAdapter : RecetaViewAdapter
private lateinit var recetas : List<Receta>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPacientePrincipalBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
idPaciente= intent.getStringExtra("IDPaciente")!!
db= RecetaDataBaseHelper(this)
recetas=db.obtenerRecetasPaciente(idPaciente)
recycleAdapter = RecetaViewAdapter(db.obtenerRecetasPaciente(idPaciente), this, this@PacientePrincipalActivity)
binding.rvRecetasPaciente.layoutManager=LinearLayoutManager(this)
binding.rvRecetasPaciente.adapter= recycleAdapter
}
override fun onResume() {
super.onResume()
recycleAdapter.refreshData(db.obtenerRecetasPaciente(idPaciente))
}
override fun onCellClickListener(position: Int) {
val receta = recetas[position]
val nombrePaciente = receta.NombrePaciente
val nombreMeciamento=receta.nombreMedicamento
val dosisMedicamento = receta.dosis
val duracionMedicamento = receta.duracion
val fechaReceta = receta.fecha
val pesoPaciente= receta.pesoPaciente
val edadPaciente = receta.edadPaciente
val descripcionReceta ="Ejemplo de descripcion"
if(permisosPDF()){
//Toast.makeText(this@PacientePrincipalActivity, "PERMISOS CONCEDIDOS", Toast.LENGTH_SHORT).show()
generarPDF(nombrePaciente, descripcionReceta)
}else{
pedirPermisosPDF()
}
}
// función que valida si los permisos ya estan garantizados por parte del usuario
fun permisosPDF() : Boolean{
val permission1= ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)
val permission2= ContextCompat.checkSelfPermission(applicationContext, Manifest.permission.READ_EXTERNAL_STORAGE)
return permission1 == PackageManager.PERMISSION_GRANTED && permission2 == PackageManager.PERMISSION_GRANTED
}
fun pedirPermisosPDF(){
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
),200)
}
fun generarPDF(tituloReceta : String, contenidoReceta : String){
val pdfDoducment = PdfDocument()
val tituloPDF = TextPaint()
val contenido = TextPaint()
val paginaInfo = PdfDocument.PageInfo.Builder(816,1054,1).create()
val paginaReceta = pdfDoducment.startPage(paginaInfo)
val canvas = paginaReceta.canvas
tituloPDF.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
tituloPDF.textSize=30f
canvas.drawText(tituloReceta,10f,150f,tituloPDF)
contenido.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
tituloPDF.textSize=20f
val arrayContenido = contenidoReceta.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var y=200
for(i in arrayContenido.indices){
canvas.drawText(arrayContenido[i],20f,y.toFloat(),contenido)
y=y+15
}
pdfDoducment.finishPage(paginaReceta)
val file=File(Environment.getExternalStorageDirectory(),"Receta.pdf")
try {
pdfDoducment.writeTo(FileOutputStream(file))
Toast.makeText(this,"PDF CREADO CORRECTAMENTE",Toast.LENGTH_LONG).show()
}catch (e: Exception){
Toast.makeText(this,"ERROR CREAR PDF ${e.toString()}",Toast.LENGTH_LONG).show()
}
pdfDoducment.close()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode==200){
if(grantResults.isNotEmpty()){
val writeStorage = grantResults[0]==PackageManager.PERMISSION_GRANTED
val readStorage = grantResults[1]==PackageManager.PERMISSION_GRANTED
if(writeStorage && readStorage){
Toast.makeText(this@PacientePrincipalActivity, "PERMISOS CONCEDIDOS", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this@PacientePrincipalActivity, "PERMISOS DENEGADOS", Toast.LENGTH_SHORT).show()
finish()
}
}
}
}
}

View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PacientePrincipalActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/rv_recetas_paciente"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
tools:listitem="@layout/rc_receta_item"
/>
</RelativeLayout>

View File

@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="100dp"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_marginEnd="12dp"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="10dp"
app:cardCornerRadius="20dp"
app:cardElevation="8dp"
android:layout_marginStart="12dp"
>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/tv_titulo_receta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="231dp"
android:layout_marginBottom="42dp"
android:hint="Titulo de la Receta"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.571" />
<TextView
android:id="@+id/tv_fecha_receta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="57dp"
android:layout_marginEnd="221dp"
android:hint="Fecha de la Receta"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<Button
android:id="@+id/btn_descargar_receta"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="243dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="24dp"
android:layout_marginBottom="10dp"
android:text="Descargar"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>