Przeglądaj źródła

fixing upload problem (news)

dola 1 rok temu
rodzic
commit
cecf9c2d85

+ 3 - 0
app/src/main/AndroidManifest.xml

@@ -7,6 +7,9 @@
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" tools:ignore="ScopedStorage" />
 
     <application
         android:name=".app.App"

+ 42 - 0
app/src/main/java/com/sambath/kunkhmer/app/MainActivity.kt

@@ -1,7 +1,11 @@
 package com.sambath.kunkhmer.app
 
+import android.Manifest
+import android.content.pm.PackageManager
 import androidx.appcompat.app.AppCompatActivity
 import android.os.Bundle
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
 import androidx.navigation.findNavController
 import androidx.navigation.ui.AppBarConfiguration
 import androidx.navigation.ui.setupWithNavController
@@ -18,6 +22,11 @@ class MainActivity : AppCompatActivity(), FighterFragment.TabSelectionListener {
     lateinit var navView: BottomNavigationView
     private lateinit var user: User
 
+    // Define a constant at the top of your class or in a companion object
+    companion object {
+        private const val STORAGE_PERMISSION_REQUEST_CODE = 123
+    }
+
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main2)
@@ -42,6 +51,24 @@ class MainActivity : AppCompatActivity(), FighterFragment.TabSelectionListener {
         }
 
         user = ModelPreferencesManager.get<User>(Const.USER_KEY)!!
+
+        if (ContextCompat.checkSelfPermission(
+                this,
+                Manifest.permission.WRITE_EXTERNAL_STORAGE
+            ) == PackageManager.PERMISSION_GRANTED
+        ) {
+            // Permission already granted, proceed with your logic
+        } else {
+            // Permission not granted, request it
+            ActivityCompat.requestPermissions(
+                this,
+                arrayOf(
+                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
+                    Manifest.permission.READ_EXTERNAL_STORAGE
+                ),
+                STORAGE_PERMISSION_REQUEST_CODE
+            )
+        }
     }
 
     override fun onTabSelected(tabIndex: Int) {
@@ -50,4 +77,19 @@ class MainActivity : AppCompatActivity(), FighterFragment.TabSelectionListener {
             fragment.selectTab(tabIndex)
         }
     }
+
+    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
+        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+        when (requestCode) {
+            STORAGE_PERMISSION_REQUEST_CODE -> {
+                // Check if the permission was granted
+                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+                    // Permission granted, proceed with your logic
+                } else {
+                    // Permission denied, inform the user or take appropriate action
+                }
+            }
+            // Handle other permissions if needed
+        }
+    }
 }

+ 19 - 74
app/src/main/java/com/sambath/kunkhmer/screen/news/NewsViewModel.kt

@@ -24,13 +24,7 @@ import java.util.concurrent.TimeUnit
 import java.util.concurrent.TimeoutException
 
 data class NewsViewState(
-    val initial: Boolean = false,
-    val isProgress: Boolean = false,
-    val isLoginSuccess: Boolean = false,
-    val error: String? = null,
-    val newsData: NewsData? = null,
-    val highlightData: HighlightData? = null,
-    val createdNewsData: CreatedNews? = null
+    val initial: Boolean = false, val isProgress: Boolean = false, val isLoginSuccess: Boolean = false, val error: String? = null, val newsData: NewsData? = null, val highlightData: HighlightData? = null, val createdNewsData: CreatedNews? = null
 )
 
 class NewsViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : BaseViewModel() {
@@ -43,16 +37,11 @@ class NewsViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : Ba
         _state.value = prev().copy(isProgress = true)
 
         disposables.add(
-            apiService.getNews()
-                .timeout(10, TimeUnit.SECONDS)
-                .subscribeOn(Schedulers.io())
-                .observeOn(AndroidSchedulers.mainThread())
-                .subscribe({
+            apiService.getNews().timeout(10, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                     if (it.resultCode == 1) {
                         _state.value = prev().copy(isProgress = false, isLoginSuccess = true, newsData = it.data!!)
                     } else {
-                        _state.value =
-                            prev().copy(isProgress = false, error = "[${it.message.description}]")
+                        _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
                     }
                 }, {
                     val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
@@ -66,16 +55,11 @@ class NewsViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : Ba
         _state.value = prev().copy(isProgress = true)
 
         disposables.add(
-            apiService.getHighlights()
-                .timeout(10, TimeUnit.SECONDS)
-                .subscribeOn(Schedulers.io())
-                .observeOn(AndroidSchedulers.mainThread())
-                .subscribe({
+            apiService.getHighlights().timeout(10, TimeUnit.SECONDS).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe({
                     if (it.resultCode == 1) {
                         _state.value = prev().copy(isProgress = false, isLoginSuccess = true, highlightData = it.data!!)
                     } else {
-                        _state.value =
-                            prev().copy(isProgress = false, error = "[${it.message.description}]")
+                        _state.value = prev().copy(isProgress = false, error = "[${it.message.description}]")
                     }
                 }, {
                     val message: String = "ប្រតិបត្តិការមិនជោគជ័យ " + it.getErrorCode()
@@ -94,43 +78,11 @@ class NewsViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : Ba
         if (!upload.isNullOrEmpty()) {
             // Assuming 'upload' is a file path, you may need to modify this part based on your actual requirements
             val file = File(request.upload)
-            val filePart = MultipartBody.Part.createFormData("upload", file.name, file.asRequestBody("multipart/form-data".toMediaTypeOrNull()))
-//            val filePart = MultipartBody.Part.createFormData("upload", file.name, file.asRequestBody())
-
-//            val file = File(request.upload)
-//            val fileRequestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
-//            val filePart = MultipartBody.Part.createFormData("upload", file.name, fileRequestBody)
-//
-//
-//            val requestBody = MultipartBody.Builder()
-//                .setType(MultipartBody.FORM)
-//                .addPart(titlePart)
-//                .addPart(descPart)
-//                .addPart(filePart)
-//                .build()
-//
-//            val multipartBody = MultipartBody.Part.createFormData("request", "filename", requestBody)
-
+            val filePart = MultipartBody.Part.createFormData("upload", file.name, file.asRequestBody("image/jpg".toMediaTypeOrNull()))
             _state.value = prev().copy(isProgress = true)
 
             disposables.add(
-                apiService.createNews(titlePart, descPart,filePart)
-                    .timeout(60, TimeUnit.SECONDS)
-                    .subscribeOn(Schedulers.io())
-                    .observeOn(AndroidSchedulers.mainThread())
-//                   .retryWhen { errors ->
-//                       errors
-//                           .zipWith(Flowable.range(1, 3)) { throwable, retryCount -> Pair(throwable, retryCount) }
-//                           .flatMap { (throwable, retryCount) ->
-//                               if (throwable is TimeoutException && retryCount <= 3) {
-//                                   Flowable.timer(5, TimeUnit.SECONDS) // Retry after 5 seconds
-//                               } else {
-//                                   Flowable.error(throwable)
-//                               }
-//                           }
-//
-//                   }
-                    .subscribe({
+                apiService.createNews(titlePart, descPart, 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)
@@ -145,25 +97,18 @@ class NewsViewModel(val apiService: ApiService, val prefHelper: PrefHelper) : Ba
         } else {
             _state.value = prev().copy(isProgress = true)
 
-            disposables.add(
-                apiService.createNews(titlePart, descPart)
-                    .timeout(10, TimeUnit.SECONDS)
-                    .doOnSubscribe { Log.d("Network", "Request started") }
-                    .doOnSuccess { Log.d("Network", "Request succeeded: $it") }
-                    .doOnError { Log.e("Network", "Request failed", it) }
-                    .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)
-                    })
+            disposables.add(apiService.createNews(titlePart, descPart).timeout(10, TimeUnit.SECONDS).doOnSubscribe { Log.d("Network", "Request started") }.doOnSuccess { Log.d("Network", "Request succeeded: $it") }.doOnError { Log.e("Network", "Request failed", it) }.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)
+                })
             )
         }
     }