Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.siakad.lecturer.menu.nilai.detail
- import android.Manifest
- import android.app.Activity
- import android.content.Context
- import android.content.DialogInterface
- import android.content.Intent
- import android.content.pm.PackageManager
- import android.net.Uri
- import android.os.AsyncTask
- import android.os.Build
- import android.os.Bundle
- import android.os.Environment
- import android.util.Log
- import android.view.LayoutInflater
- import android.view.ViewGroup
- import android.webkit.MimeTypeMap
- import androidx.annotation.RequiresApi
- import androidx.appcompat.app.AlertDialog
- import androidx.appcompat.app.AppCompatActivity
- import androidx.core.app.ActivityCompat
- import androidx.core.content.ContextCompat
- import androidx.core.content.FileProvider
- import androidx.navigation.fragment.findNavController
- import androidx.recyclerview.widget.LinearLayoutManager
- import com.google.android.material.dialog.MaterialAlertDialogBuilder
- import com.siakad.lecturer.R
- import com.siakad.lecturer.activity.base.BaseFragment
- import com.siakad.lecturer.activity.dashboard.kehadiran.EntryNilaiAdapter
- import com.siakad.lecturer.config.connection.Resource
- import com.siakad.lecturer.config.crypts.EncDec
- import com.siakad.lecturer.config.endpoint.Nilai
- import com.siakad.lecturer.config.response.ResponseModel
- import com.siakad.lecturer.config.util.*
- import com.siakad.lecturer.databinding.FragmentEntryNilaiBinding
- import com.siakad.lecturer.menu.nilai.detail.upload.FormUpload
- import kotlinx.coroutines.flow.first
- import kotlinx.coroutines.runBlocking
- import okhttp3.MediaType
- import okhttp3.MultipartBody
- import okhttp3.RequestBody
- import okhttp3.ResponseBody
- import org.json.JSONObject
- import java.io.*
- class EntryNilaiFragment : BaseFragment<EntryNilaiViewModel, FragmentEntryNilaiBinding, EntryNilaiRepository>(),
- EntryNilaiAdapter.OnItemClickListener{
- private val TAG = "EntryNilaiFragment"
- val sp_nilaihuruf = arrayOf("A", "AB", "B", "BC", "C", "D", "E")
- //Tak Push Bang
- private var nilai = ""
- private var nilaiganti = ""
- private var nim = ""
- private var thnakademik = ""
- private var idmatakuliah = ""
- private var nilaibaru = ""
- private var idkelas = ""
- private var kelas = ""
- private val NILAI_PICK = 111
- private val REQUEST_STORAGE_PERMISSION = 101
- var select_file: String? = null
- var kind = 0
- override fun onActivityCreated(savedInstanceState: Bundle?) {
- super.onActivityCreated(savedInstanceState)
- val tokens = runBlocking { userPrefrences.authToken.first()}
- (activity as AppCompatActivity).setSupportActionBar(binding.topAppBar)
- binding.topAppBar.apply {
- navigationIcon = ContextCompat.getDrawable(context, R.drawable.ic_back)
- setNavigationOnClickListener {
- findNavController().popBackStack()
- }
- }
- kelas = "${arguments?.getString("kelas")}"
- binding.btDownload.setOnClickListener {
- if (hasReadPermission()) {
- downloadNilai()
- } else {
- context?.let { it1 ->
- AlertDialogManager.DialogPermisssion(it1, ".")
- .setPositiveButton(
- "Aktifkan".toLowerCase()
- ) { dialog: DialogInterface, which: Int ->
- ActivityCompat.requestPermissions(
- context as Activity,
- arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
- REQUEST_STORAGE_PERMISSION
- )
- dialog.dismiss()
- }.show()
- }
- }
- }
- binding.btUpload.setOnClickListener {
- when(kind) {
- 0 -> {
- if (hasReadPermission()) {
- pick_file()
- } else {
- AlertDialogManager.DialogPermisssion(requireContext(), ".")
- .setPositiveButton(
- "Aktifkan".toLowerCase()
- ) { dialog: DialogInterface, which: Int ->
- ActivityCompat.requestPermissions(requireActivity(),
- arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
- REQUEST_STORAGE_PERMISSION)
- dialog.dismiss()
- }.show()
- }
- }
- 1 -> {
- val bottomSheetFragment = FormUpload()
- bottomSheetFragment.show(requireActivity().supportFragmentManager, bottomSheetFragment.tag)
- }
- }
- }
- nilaiPeserta()
- }
- private fun nilaiPeserta(){
- try {
- val jsonOb = JSONObject()
- jsonOb.put("idkelas", arguments?.getString("idkelas"))
- Log.e(TAG, "idkelase: ${arguments?.getString("idkelas")}")
- val param = EncDec().toEncrypt(jsonOb.toString())
- val streams = param?.replace("\\n", "")
- streams?.let { it -> viewModel.nilaiModel(it) }
- val progressDialogManager = context?.let { it -> ProgressDialogManager(it).loader("Sedang memuat data") }
- viewModel.nilaiPesertaResponse.observe(viewLifecycleOwner) {
- when (it) {
- is Resource.Loading -> progressDialogManager?.show()
- is Resource.Success -> {
- val responseModel: ResponseModel = it.value
- val decrypt = EncDec().toDerypt(responseModel.streams)
- Log.e(TAG, "nilaiPeserta: $decrypt", )
- val jsonObject = JSONObject(decrypt)
- val jsonArray = jsonObject.getJSONArray("data")
- thnakademik = jsonObject.getString("thnakademik")
- idmatakuliah = jsonObject.getString("idmatakuliah")
- val list = ArrayList<EntryNilaiPesertaModel>()
- for (i in 0 until jsonArray.length()) {
- val model = EntryNilaiPesertaModel(
- jsonArray.getJSONObject(i).getString("nama"),
- jsonArray.getJSONObject(i).getString("penginput"),
- jsonArray.getJSONObject(i).getString("idkelas"),
- jsonArray.getJSONObject(i).getString("nim"),
- jsonArray.getJSONObject(i).getString("namaprogramstudi"),
- jsonArray.getJSONObject(i).getString("nilaihuruf"),
- jsonArray.getJSONObject(i).getString("stskehadiran")
- )
- list.add(model)
- }
- val entryNilaiAdapter = context?.let { it -> EntryNilaiAdapter(it, list) }
- binding.rcEntryNilai.apply {
- layoutManager = LinearLayoutManager(
- context,
- LinearLayoutManager.VERTICAL,
- false
- )
- setHasFixedSize(true)
- adapter = entryNilaiAdapter
- }
- entryNilaiAdapter?.setOnItemClickListener(this)
- progressDialogManager?.dismiss()
- }
- is Resource.Failure -> {
- progressDialogManager?.dismiss()
- handleApiError(it)
- }
- }
- }
- } catch (e: Exception){
- e.printStackTrace()
- }
- }
- override fun onItemClick(item: EntryNilaiAdapter.ViewHolder?, position: Int) {
- val alertDialog = AlertDialog.Builder(requireContext())
- alertDialog.setTitle("Rubah Nilai")
- alertDialog.setSingleChoiceItems(sp_nilaihuruf, -1) { _, which ->
- nilaiganti = sp_nilaihuruf[which]
- }
- alertDialog.setPositiveButton("OK") { dialog, which ->
- nilaibaru = nilaiganti
- nim = item!!.parent.getNim()
- idkelas = item.parent.getIdKelas()
- gantiNilaiPeserta()
- Log.e("TAG", "onItemClick nim: " + item.parent.getNim())
- }
- alertDialog.setNegativeButton("Tutup") { dialog, which ->
- dialog.dismiss()
- }
- if (nilai == "0") {
- alertNoEdit()
- } else {
- alertDialog.show()
- }
- }
- private fun alertNoEdit() {
- val alertDialog = AlertDialog.Builder(requireContext())
- alertDialog.setTitle("Rubah Nilai")
- alertDialog.setMessage("Tidak Bisa Merubah Nilai")
- alertDialog.setPositiveButton("Ok") { dialogInterface, i -> dialogInterface.dismiss() }
- alertDialog.show()
- }
- private fun gantiNilaiPeserta(){
- try {
- val jsonObject = JSONObject()
- jsonObject.put("idkelas", idkelas)
- jsonObject.put("nim", nim)
- jsonObject.put("thnakademik", thnakademik)
- jsonObject.put("idmatakuliah", idmatakuliah)
- jsonObject.put("nilai", nilaibaru)
- Log.e(TAG, "AKUSOPO?: $jsonObject", )
- val param = EncDec().toEncrypt(jsonObject.toString())
- val streams = param?.replace("\\n", "")
- streams?.let { it -> viewModel.gantiNilaiModel(it) }
- val progressDialogManager = context?.let { it -> ProgressDialogManager(it).loader("Sedang mengirim data") }
- viewModel.gantinilaiPesertaResponse.observe(viewLifecycleOwner) {
- when (it) {
- is Resource.Loading -> progressDialogManager?.show()
- is Resource.Success -> {
- val responseModel: ResponseModel = it.value
- val decrypt = EncDec().toDerypt(responseModel.streams)
- val message = responseModel.message
- // context?.let { it ->
- // MaterialAlertDialogBuilder(it)
- // .setTitle("Siakad Lecturer")
- // .setMessage(message)
- // .setCancelable(false)
- // .setPositiveButton("Ok") { dialog, which ->
- //// findNavController().navigate(R.id.action_entryNilaiFragment_self)
- // nilaiPeserta()
- // dialog.dismiss()
- // }
- // .show()
- // }
- progressDialogManager?.dismiss()
- nilaiPeserta()
- requireView().snackbar(message)
- }
- is Resource.Failure -> {
- progressDialogManager?.dismiss()
- handleApiError(it)
- }
- }
- }
- } catch (e: Exception){
- e.printStackTrace()
- }
- }
- private fun downloadNilai() {
- try {
- val jsonOb = JSONObject()
- jsonOb.put("idmatakuliah", idmatakuliah)
- jsonOb.put("idkelas", arguments?.getString("idkelas"))
- Log.e(TAG, "downloadNilai: $idmatakuliah", )
- val param = EncDec().toEncrypt(jsonOb.toString())
- val streams = param?.replace("\\n", "")
- streams?.let { it -> viewModel.downloadNilaiModel(it) }
- val progressDialogManager = context?.let { it -> ProgressDialogManager(it).loader("Sedang mendownload nilai") }
- viewModel.downloadNilaiResponse.observe(viewLifecycleOwner) {
- when (it) {
- is Resource.Loading -> progressDialogManager?.show()
- is Resource.Success -> {
- val responseBody: ResponseBody = it.value
- val downloadFileAsyncTask = DownloadFileAsyncTask(
- context as Activity,
- "$kelas ${System.currentTimeMillis()}",
- ".xlsx"
- )
- downloadFileAsyncTask.execute(responseBody.byteStream())
- progressDialogManager?.dismiss()
- }
- is Resource.Failure -> {
- progressDialogManager?.dismiss()
- handleApiError(it)
- }
- }
- }
- } catch (e: Exception){
- e.printStackTrace()
- }
- }
- private class DownloadFileAsyncTask(
- val activity: Activity,
- file_name: String?,
- format: String?
- ) : AsyncTask<InputStream, Void, Boolean>() {
- var builder: MaterialAlertDialogBuilder? = null
- val appDirectoryName = "SML_File"
- val jurnalFile = File(
- Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
- appDirectoryName
- )
- val ext = format
- val filename = file_name
- override fun doInBackground(vararg params: InputStream?): Boolean {
- if(!jurnalFile.isDirectory) {
- jurnalFile.mkdirs() // create Folder
- }
- val inputStream = params[0]!!
- val file = File(jurnalFile, "$filename$ext")
- var output: OutputStream? = null
- try {
- output = FileOutputStream(file)
- val buffer = ByteArray(1024)
- var read: Int
- Log.d("TAG", "nyimpen >> $jurnalFile/$filename")
- while (inputStream.read(buffer).also { read = it } != -1) {
- output.write(buffer, 0, read)
- }
- output.flush()
- } catch (e: IOException) {
- e.printStackTrace()
- return false
- } finally {
- try {
- if (output != null) {
- output.close()
- } else {
- Log.d("TAG", "Output stream e null")
- }
- } catch (e: IOException) {
- Log.e("TAG", ">> " + e.message)
- e.printStackTrace()
- return false
- }
- }
- return true
- }
- override fun onPostExecute(result: Boolean?) {
- super.onPostExecute(result)
- MaterialAlertDialogBuilder(activity)
- .setTitle(R.string.app_name)
- .setIcon(R.mipmap.ic_launcher)
- .setMessage("Jurnal $filename Berhasil di download")
- .setPositiveButton("Buka File") { dialog, which ->
- openFiles()
- }
- .setNegativeButton("Nanti saja") { dialog, which ->
- dialog.dismiss()
- }
- .show()
- }
- fun openFiles() {
- val appDirectoryName = "SML_File"
- val file = File(
- Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
- "$appDirectoryName/$filename$ext"
- )
- Log.e("ape mbukak iki ==>", "" + file)
- val uri = FileProvider.getUriForFile(
- activity,
- "com.siakad.lecturer.fileprovider",
- file
- )
- Log.e("create pdf uri path==>", "" + uri)
- val intent = Intent(Intent.ACTION_VIEW)
- intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
- intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
- if (file.toString().contains(".doc") || file.toString().contains(".docx")) {
- // Word document
- intent.setDataAndType(uri, "application/msword")
- } else if(file.toString().contains(".pdf")) {
- // PDF file
- intent.setDataAndType(uri, "application/pdf")
- } else if(file.toString().contains(".ppt") || file.toString().contains(".pptx")) {
- // Powerpoint file
- intent.setDataAndType(uri, "application/vnd.ms-powerpoint")
- } else if(file.toString().contains(".xls") || file.toString().contains(".xlsx")) {
- // Excel file
- intent.setDataAndType(uri, "application/vnd.ms-excel")
- } else if(file.toString().contains(".jpg") || file.toString().contains(".jpeg")) {
- // jpeg/jpg file
- intent.setDataAndType(uri, "image/jpeg")
- } else {
- intent.setDataAndType(uri, "*/*")
- }
- activity.startActivity(Intent.createChooser(intent, "Buka Jurnal $filename"))
- }
- }
- private fun hasReadPermission(): Boolean {
- return context?.let { ActivityCompat.checkSelfPermission(
- it,
- Manifest.permission.WRITE_EXTERNAL_STORAGE
- ) } == PackageManager.PERMISSION_GRANTED
- }
- override fun onRequestPermissionsResult(
- requestCode: Int,
- permissions: Array<out String>,
- grantResults: IntArray
- ) {
- super.onRequestPermissionsResult(requestCode, permissions, grantResults)
- if (requestCode == REQUEST_STORAGE_PERMISSION) {
- if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- downloadNilai()
- }
- }
- }
- override fun getViewModel() = EntryNilaiViewModel::class.java
- private fun pick_file() {
- val intent = Intent()
- intent.type = "*/*"
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- intent.action = Intent.ACTION_OPEN_DOCUMENT
- } else {
- intent.action = Intent.ACTION_OPEN_DOCUMENT
- }
- intent.addCategory(Intent.CATEGORY_OPENABLE)
- intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true)
- startActivityForResult(Intent.createChooser(intent, "Select a file"), NILAI_PICK)
- }
- override fun getFragmentBinding(
- inflater: LayoutInflater,
- container: ViewGroup?
- ) = FragmentEntryNilaiBinding.inflate(inflater, container, false)
- override fun getFragmentRepository(): EntryNilaiRepository {
- val token = runBlocking { userPrefrences.authToken.first() }
- val api = clientRemote.buildApi(Nilai::class.java, token)
- return EntryNilaiRepository(api)
- }
- @RequiresApi(Build.VERSION_CODES.KITKAT)
- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
- super.onActivityResult(requestCode, resultCode, data)
- if (requestCode == NILAI_PICK && resultCode == AppCompatActivity.RESULT_OK) {
- val selectedFileUri = data?.data //The uri with the location of the file
- val takeFlags = data?.flags?.and((Intent.FLAG_GRANT_READ_URI_PERMISSION
- or Intent.FLAG_GRANT_WRITE_URI_PERMISSION))
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
- if (selectedFileUri != null) {
- requireActivity().contentResolver.takePersistableUriPermission(selectedFileUri, takeFlags!!)
- }
- }
- var uriString: String = selectedFileUri.toString()
- val file = File(uriString)
- val path: String = FileUtils.getPath(context, selectedFileUri)
- uploadNilai(selectedFileUri)
- }
- }
- private fun uploadNilai(path: Uri?) {
- try {
- Log.e(TAG, "onActivityResult: ${context?.let { path?.let { it1 -> fileFromContentUri(it, it1) } }}" )
- val mFile = RequestBody.create(MediaType.parse("application/vnd.ms-excel"), context?.let { path?.let { it1 -> fileFromContentUri(it, it1) } })
- val excelUpload = MultipartBody.Part.createFormData("template", context?.let { FileUtils.getFileName(it, path) }, mFile)
- val idmatakuliah = RequestBody.create(MediaType.parse("text/plain"), idmatakuliah)
- val idstafdosen = RequestBody.create(MediaType.parse("text/plain"), runBlocking { userPrefrences.idStafDosenFlow.first() })
- viewModel.uploadNilaiModel(idmatakuliah, idstafdosen, excelUpload)
- val progressDialogManager = context?.let { it -> ProgressDialogManager(it).loader("Sedang mengirim data") }
- viewModel.uploadNilaiResponse.observe(viewLifecycleOwner) {
- when (it) {
- is Resource.Loading -> progressDialogManager?.show()
- is Resource.Success -> {
- val responseModel: ResponseModel = it.value
- val decrypt = EncDec().toDerypt(responseModel.streams)
- Log.e("TAG", "upload : $decrypt")
- progressDialogManager?.dismiss()
- }
- is Resource.Failure -> {
- progressDialogManager?.dismiss()
- handleApiError(it)
- Log.e(TAG, "uploadNilai: ${it}")
- }
- }
- }
- } catch (e: Exception){
- e.printStackTrace()
- }
- }
- fun fileFromContentUri(context: Context, contentUri: Uri): File {
- // Preparing Temp file name
- val fileExtension = getFileExtension(context, contentUri)
- val fileName = "temp_file"+ if (fileExtension != null) ".$fileExtension" else ""
- // Creating Temp file
- val tempFile = File(context.cacheDir, fileName)
- tempFile.createNewFile()
- try {
- val oStream = FileOutputStream(tempFile)
- val inputStream = context.contentResolver.openInputStream(contentUri)
- inputStream?.let {
- copy(inputStream, oStream)
- }
- oStream.flush()
- } catch (e: Exception) {
- e.printStackTrace()
- }
- return tempFile
- }
- private fun getFileExtension(context: Context, uri: Uri): String? {
- val fileType: String? = context.contentResolver.getType(uri)
- return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
- }
- @Throws(IOException::class)
- private fun copy(source: InputStream, target: OutputStream) {
- val buf = ByteArray(8192)
- var length: Int
- while (source.read(buf).also { length = it } > 0) {
- target.write(buf, 0, length)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement