android java.lang.NumberFormatException:对于输入字符串:”“在Kotlin中

jtoj6r0c  于 2023-05-12  发布在  Android
关注(0)|答案(2)|浏览(195)

我想当用户按下图像导航到细节片段,但当按下其崩溃,并显示NumberFormat的错误,即使我把toInt处理异常,我试图在这里做一些解决方案,但没有工作
这是我的详细信息片段的代码:

package com.example.finalcapstone_nomapp.main.view

import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Canvas
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.StrictMode
import android.provider.MediaStore
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.activityViewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.example.finalcapstone_nomapp.R
import com.example.finalcapstone_nomapp.databinding.FragmentDetailsBinding
import com.example.finalcapstone_nomapp.model.Result
import com.squareup.picasso.Picasso
import java.io.ByteArrayOutputStream
import java.lang.NumberFormatException

class DetailsFragment : Fragment() {
      private lateinit var binding : FragmentDetailsBinding
      private val recipesViewModel : RecipesViewModel by activityViewModels()
    private val favoriteRecipesViewModel : FavoriteRecipesViewModel by activityViewModels()
    lateinit var favoriteItem : Result

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

       binding = FragmentDetailsBinding.inflate(layoutInflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
       
        val result = Result(
            recipesViewModel.likes.toInt(),
            true,
            true,
            true,
            recipesViewModel.id.toInt(),
            recipesViewModel.image,
            recipesViewModel.ready,
            "url",
            recipesViewModel.description,
            recipesViewModel.title,
            recipesViewModel.vegan,
            true,
            true
        )
        observers()

        binding.addImageView.setOnClickListener(){
            observers()
            favoriteRecipesViewModel.addFavoriteRecipe(result,"")
            findNavController().navigate(R.id.action_detailsFragment_to_FavoriteFragment)

            if (binding.addImageView.isPressed){
               binding.addImageView.setImageResource(R.drawable.addimageviewblack)
            }
        }
        binding.recipeDetailsImageView2.setOnClickListener {
            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(favoriteItem.sourceUrl))
            startActivity(intent)
        }
    }

    @SuppressLint("ResourceAsColor")
    fun observers(){
        recipesViewModel.selectedRecipeMutabileLiveData.observe(viewLifecycleOwner,{

            var selectedItem = it
        //================================================================//
            Picasso.get().load(it.image).into(binding.recipeDetailsImageView2)

        //================================================================//
            binding.detailTitleTextView.text = it.title
            binding.detailLikesTextView.text = it.aggregateLikes.toString()
            binding.detailsTimeTextView.text = it.readyInMinutes.toString()

        //=================================================================//
            binding.summaryTextView.text = it.summary
         //==================================================================//

            when {
                it.vegetarian -> {
                    binding.detailVegetarianImageView.setImageResource(R.drawable.check)
                    binding.detailVeganTextView.setTextColor(R.color.green)
                }
                it.vegan -> {

                    binding.detailVeganImageView.setImageResource(R.drawable.check)
                    binding.detailVeganTextView.setTextColor(R.color.green)
                }
                it.dairyFree -> {
                    binding.detailDairyfreeImageView.setImageResource(R.drawable.check)
                    binding.detailDairyfreeTextView.setTextColor(R.color.green)

                }
                it.glutenFree -> {
                    binding.detailGlutenfreeImageView.setImageResource(R.drawable.check)
                    binding.detailGlutenfreeTextView.setTextColor(R.color.green)

                }
                it.veryHealthy -> {
                    binding.detailHealthyImageView.setImageResource(R.drawable.check)
                    binding.detailGlutenfreeTextView.setTextColor(R.color.green)

                }
                it.cheap -> {
                    binding.detailCheapImageView.setImageResource(R.drawable.check)
                    binding.detailCheapTextView.setTextColor(R.color.green)
                }
            }
        })
    }
}

下面是我的recipesViewModel代码:

package com.example.finalcapstone_nomapp.main.view

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.finalcapstone_nomapp.main.adapters.RecipesAdapter
import com.example.finalcapstone_nomapp.model.Result
import com.example.finalcapstone_nomapp.repository.ApiRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlin.Exception

private const val TAG = "RecipesViewModel"

class RecipesViewModel : ViewModel() {

    // Getting instance from ApiRepository with companion object function

    private val apiRepo = ApiRepository.get()

    private lateinit var recipesAdapter : RecipesAdapter

    // livedata
    val recipesLiveData = MutableLiveData<List<Result>>()
    val recipesErrorLiveData = MutableLiveData<String>()
    
    var selectedRecipeMutabileLiveData = MutableLiveData<Result>()

    var likes = ""
    var id = ""
    var image = ""
    var ready = 0
    var description = ""
    var title = ""
    var vegan = true

    //=========================================================//
    fun callRecipes(){
     //coroutine in this scope will live as long the view model is alive.
        viewModelScope.launch(Dispatchers.IO) {
          // use try and catch to handle http exceptions

            try {

                val response = apiRepo.getRecipes("String",true,true,"String")

                if (response.isSuccessful){
                    response.body()?.run {
                        Log.d(TAG,this.toString())

                        recipesLiveData.postValue(this.results)
                        Log.d(TAG, "success response ${response.body()}")
                    }
                }else{
                    Log.d(TAG,"NOT SUCCESS ${response.message()}")
                    recipesErrorLiveData.postValue(response.message())

                }
            } catch (e : Exception){
                Log.d(TAG,e.message.toString())
                recipesErrorLiveData.postValue(e.message.toString())
            }
        }
    }
}
nlejzf6q

nlejzf6q1#

问题就在这里:

var likes = ""
var id = ""

recipesViewModel.likes.toInt(),
recipesViewModel.id.toInt(),

当字符串为空或空白时尝试跳过分析

...
safeToInt(recipesViewModel.id)

fun safeToInt(string: String): Int {
    if (string.isNotBlank()) {
        return string.toInt()
    } else {
// or other logic
        return 0
    }
}
...
ego6inou

ego6inou2#

很抱歉晚才出现,请阅读此安全类型的原始铸造。

**toInt()**方法帮助将字符串解析为Int数值。但是,如果它发现字符串不是数字值的正确表示形式,则会引发NumberFormatException异常。
**toIntOrNull()**方法将字符串解析为Int,如果发现字符串不属于有效的数值表示,则返回null。

相关问题