Prechádzať zdrojové kódy

fixing upload problem (news)

dola 10 mesiacov pred
rodič
commit
9fb11aedde

+ 10 - 0
app/src/main/java/com/sambath/kunkhmer/remote/FighterDataModel.kt

@@ -122,4 +122,14 @@ data class CreatedMatch(
 
     @Json(name = "__v")
     val _v: Int,
+)
+
+///
+
+@JsonClass(generateAdapter = true)
+data class CreateFighterResponse(
+    @Json(name = "code")
+    val resultCode: Int,
+    @Json(name = "message")
+    val message: ResponseMessage,
 )

+ 17 - 0
app/src/main/java/com/sambath/kunkhmer/remote/service/ApiService.kt

@@ -67,6 +67,23 @@ interface ApiService {
                       @Part("price") price: RequestBody
                       ): Single<CreateProductResponse>
 
+    @Multipart
+    @POST("/v1/fighter/create")
+    fun createFighter(@Part("name") name: RequestBody,
+                      @Part("desc") desc: RequestBody,
+                      @Part("weight") price: RequestBody,
+                      @Part("high") height: RequestBody,
+                      @Part("nationality") nationality: RequestBody,
+                      @Part file: MultipartBody.Part): Single<CreateFighterResponse>
+
+    @Multipart
+    @POST("/v1/fighter/create")
+    fun createFighter(@Part("name") name: RequestBody,
+                      @Part("desc") desc: RequestBody,
+                      @Part("weight") price: RequestBody,
+                      @Part("high") height: RequestBody,
+                      @Part("nationality") nationality: RequestBody): Single<CreateFighterResponse>
+
     @POST("/v1/highLight/create")
     fun createHighlight(@Body createHighlightRequest: CreateHighlightRequest): Single<CreateHighlightResponse>
 

+ 103 - 0
app/src/main/java/com/sambath/kunkhmer/screen/fighter/CreateFighterFragment.kt

@@ -1,16 +1,34 @@
 package com.sambath.kunkhmer.screen.fighter
 
+import android.app.Activity
+import android.content.Intent
+import android.net.Uri
 import android.os.Bundle
+import android.provider.MediaStore
 import androidx.fragment.app.Fragment
 import android.view.LayoutInflater
 import android.view.View
 import android.view.ViewGroup
+import android.widget.Toast
+import androidx.activity.result.ActivityResultLauncher
+import androidx.activity.result.contract.ActivityResultContracts
 import com.sambath.kunkhmer.R
+import com.sambath.kunkhmer.app.App
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_desc
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_height
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_name
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_nationality
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.et_weight
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.submitButton
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.uploadButton
+import kotlinx.android.synthetic.main.fragment_create_fighter.view.uploadedImageView
 
 
 class CreateFighterFragment : Fragment() {
     private var _root: View? = null
     private val binding get() = _root!!
+    private var imageUri: Uri? = null
+    private lateinit var fighterViewModel: FighterViewModel
 
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
@@ -20,6 +38,91 @@ class CreateFighterFragment : Fragment() {
         // Inflate the layout for this fragment
         _root = inflater.inflate(R.layout.fragment_create_fighter, container, false)
 
+        fighterViewModel = FighterViewModel(App.injectApiService(), App.injectPrefHelper())
+        fighterViewModel.state.observe(viewLifecycleOwner, androidx.lifecycle.Observer {
+            render(it)
+        })
+
+        binding.uploadButton.setOnClickListener {
+            openImagePicker()
+        }
+
+        binding.submitButton.setOnClickListener {
+            val imagePath = imageUri?.let { it1 -> getImagePathFromUri(it1) }
+            if (imagePath != null) {
+                fighterViewModel.createFighter(
+                    binding.et_name.text.toString(),
+                    binding.et_desc.text.toString(),
+                    binding.et_weight.text.toString(),
+                    binding.et_height.text.toString(),
+                    binding.et_nationality.text.toString(),
+                    imagePath
+                )
+            } else {
+                fighterViewModel.createFighter(
+                    binding.et_name.text.toString(),
+                    binding.et_desc.text.toString(),
+                    binding.et_weight.text.toString(),
+                    binding.et_height.text.toString(),
+                    binding.et_nationality.text.toString(),
+                    ""
+                )
+            }
+        }
+
+        setDefault()
         return binding
     }
+
+    private fun render(state: FighterViewState) {
+        if (state.isLoginSuccess) {
+            Toast.makeText(context, "Create Success...", Toast.LENGTH_LONG).show()
+
+            binding.et_name.setText("")
+            binding.et_desc.setText("")
+            binding.et_weight.setText("")
+            binding.et_height.setText("")
+            binding.et_nationality.setText("")
+            binding.uploadedImageView.setImageDrawable(null)
+        }
+    }
+
+    private val imagePicker: ActivityResultLauncher<Intent> =
+        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
+            if (result.resultCode == Activity.RESULT_OK) {
+                val data: Intent? = result.data
+                if (data != null) {
+                    imageUri = data.data // The URI of the selected image
+                    if (imageUri != null) {
+                        // Load and display the selected image in the ImageView
+                        binding.uploadedImageView.setImageURI(imageUri)
+                    }
+                }
+            }
+        }
+
+    private fun openImagePicker() {
+        val intent = Intent(Intent.ACTION_GET_CONTENT)
+        intent.type = "image/*"
+        imagePicker.launch(intent)
+    }
+
+    private fun getImagePathFromUri(uri: Uri): String? {
+        val contentResolver = requireContext().contentResolver
+        val cursor = contentResolver.query(uri, null, null, null, null)
+        cursor?.use {
+            it.moveToFirst()
+            val index = it.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
+            return it.getString(index)
+        }
+        return null
+    }
+
+    private fun setDefault() {
+        binding.et_name.setText("John Cena")
+        binding.et_desc.setText("John Cena")
+        binding.et_weight.setText("66")
+        binding.et_height.setText("1,75")
+        binding.et_nationality.setText("US")
+    }
 }

+ 52 - 18
app/src/main/java/com/sambath/kunkhmer/screen/fighter/FighterViewModel.kt

@@ -14,7 +14,12 @@ import com.sambath.kunkhmer.remote.service.ApiService
 import com.sambath.kunkhmer.util.PrefHelper
 import io.reactivex.android.schedulers.AndroidSchedulers
 import io.reactivex.schedulers.Schedulers
+import okhttp3.MediaType.Companion.toMediaTypeOrNull
+import okhttp3.MultipartBody
+import okhttp3.RequestBody.Companion.asRequestBody
+import okhttp3.RequestBody.Companion.toRequestBody
 import okhttp3.ResponseBody
+import java.io.File
 import java.util.concurrent.TimeUnit
 
 class FighterViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel() {
@@ -69,26 +74,55 @@ class FighterViewModel(val apiService: ApiService, val prefHelper: PrefHelper) :
         )
     }
 
-    fun getFighterImage(imageUrl: String): LiveData<Bitmap?> {
-        val imageLiveData = MutableLiveData<Bitmap?>()
-        disposables.add(apiService.getFighterImage(imageUrl)
-            .map { responseBody -> processResponseIntoImage(responseBody) }
-            .subscribeOn(Schedulers.io())
-            .observeOn(AndroidSchedulers.mainThread())
-            .subscribe({ bitmap ->
-                imageLiveData.value = bitmap
-            }, { throwable ->
-                Log.e("FighterViewModel", "Error getting image", throwable)
-            })
-        )
-        return imageLiveData
-    }
+    fun createFighter(name: String, desc: String, weight: String, height: String, nationality: String, upload: String) {
+        if (_state.value!!.isProgress) return
+
+        val namePart = name.toRequestBody("text/plain".toMediaTypeOrNull())
+        val descPart = desc.toRequestBody("text/plain".toMediaTypeOrNull())
+        val weightPart = weight.toRequestBody("text/plain".toMediaTypeOrNull())
+        val heightPart = height.toRequestBody("text/plain".toMediaTypeOrNull())
+        val nationalityPart = nationality.toRequestBody("text/plain".toMediaTypeOrNull())
+
+        if (!upload.isNullOrEmpty()) {
+            val file = File(upload)
+            val filePart = MultipartBody.Part.createFormData("upload", file.name, file.asRequestBody("image/jpg".toMediaTypeOrNull()))
+            _state.value = prev().copy(isProgress = true)
 
-    private fun processResponseIntoImage(responseBody: ResponseBody): Bitmap? {
-        return if (responseBody.contentLength() > 0) {
-            BitmapFactory.decodeStream(responseBody.byteStream())
+            disposables.add(
+                apiService.createFighter(namePart, descPart, weightPart, heightPart, nationalityPart, filePart)
+                    .timeout(60, TimeUnit.SECONDS)
+                    .subscribeOn(Schedulers.io())
+                    .observeOn(AndroidSchedulers.mainThread())
+                    .subscribe({
+                        Log.d("login", it.toString())
+                        if (it.resultCode == 1) {
+                            _state.value = prev().copy(isProgress = false, isLoginSuccess = true)
+                        } else {
+                            _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
+                        }
+                    }, {
+                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
+                        _state.value = prev().copy(isProgress = false, error = message)
+                    })
+            )
         } else {
-            null
+            disposables.add(
+                apiService.createFighter(namePart, descPart, weightPart, heightPart, nationalityPart)
+                    .timeout(60, TimeUnit.SECONDS)
+                    .subscribeOn(Schedulers.io())
+                    .observeOn(AndroidSchedulers.mainThread())
+                    .subscribe({
+                        Log.d("login", it.toString())
+                        if (it.resultCode == 1) {
+                            _state.value = prev().copy(isProgress = false, isLoginSuccess = true)
+                        } else {
+                            _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
+                        }
+                    }, {
+                        val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
+                        _state.value = prev().copy(isProgress = false, error = message)
+                    })
+            )
         }
     }
 }

+ 10 - 0
app/src/main/res/layout/fragment_create_fighter.xml

@@ -123,4 +123,14 @@
         android:background="@color/color_gray_300"
         android:scaleType="centerCrop" />
 
+    <Button
+        android:id="@+id/submitButton"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:layout_marginBottom="16dp"
+        android:paddingStart="16dp"
+        android:paddingEnd="16dp"
+        android:text="Submit" />
+
 </androidx.appcompat.widget.LinearLayoutCompat>