-1

Here's the code where i am getting exception, tried various ways to implement context but nothing is working out. class GrowthStoryFragment : Fragment() {

private val TAG = "GrowthStoryFragment"


companion object{

    private var countryID = "1"
    private var date = "MAT TY"
    private var spec  = "val"

    private var businessUnitID = "2"
    private var category = "Fresh Milk"
    private var firstReportTypeId = "1"       //fixed for growth story and share story
    private var isGroup = "false"             //fixed to false
}

private val backendApi = WinRetrofitHelper.winApiInstance()

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_growth_story, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    getSpinnerResponse(businessUnitID, isGroup,firstReportTypeId)
    getSuperRegionName(countryID, date,spec," ",businessUnitID, category, firstReportTypeId, isGroup)

    growth_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
        override fun onNothingSelected(parent: AdapterView<*>?) {

        }

        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
            val item  = parent?.getItemAtPosition(position) as RespTwo
            category = item.nameValue
            Log.e(TAG,"Category name is: " + category)
            getSuperRegionName(countryID, date,spec," ",businessUnitID, category, firstReportTypeId, isGroup)
        }

    }
}

private fun getSpinnerResponse(businessUnitID: String, isGroup: String, firstReportTypeId: String){
    val request =   backendApi.getCategoryBusinessUnit(businessUnitID, isGroup, firstReportTypeId)

    request.enqueue(object : Callback<List<RespTwo>> {
        override fun onFailure(call: Call<List<RespTwo>>?, t: Throwable?) {
            Log.e(TAG, "Failure Super Region Name: ")
        }

        override fun onResponse(call: Call<List<RespTwo>>?, response: Response<List<RespTwo>>?) {
            val myresponse = response?.body()
            if (response?.body() != null && !response?.body()!!.isEmpty()) {

                growth_spinner.adapter = GrowthSpinnerAdapter(response?.body())
                Log.e(TAG, "Super Region Name: " + myresponse?.get(0)?.nameValue)
            } else {
                Toast.makeText(context!!.applicationContext, "Data Not Available!", Toast.LENGTH_LONG).show()

            }
        }
    })
}

private fun getSuperRegionName(countryID: String, date: String, spec: String, superMarket: String,businessUnitID: String, category: String, firstReportTypeId: String, isGroup: String) {
    val request = backendApi.getSuperRegion(countryID)

    request.enqueue(object : Callback<List<RespMy>> {
        override fun onFailure(call: Call<List<RespMy>>?, t: Throwable?) {
            Log.e(TAG, "Failure Super Region Name: ")
        }

        override fun onResponse(call: Call<List<RespMy>>?, response: Response<List<RespMy>>?) {
            val myresponse = response?.body()
            if (response?.body() != null && !response?.body()!!.isEmpty()) {

                getDataFromApi(countryID, date, spec, myresponse?.get(0)!!.nameValue, businessUnitID, category, firstReportTypeId, isGroup)
                Log.e(TAG, "Super Region Name: " +countryID+" "+ date+" "+ spec+" "+ myresponse?.get(0)?.nameValue+" "+businessUnitID+" "+ category+" "+ firstReportTypeId+" " + isGroup+" ")
            } else {
                Toast.makeText(myApplicationContext, "Data Not Available!", Toast.LENGTH_LONG).show()

            }
        }
    })
}

} Please suggest something and i have heard a viewModel conversion of the requests made directly from fragments can fix this out but i don't know how to do that. Please help in either way.

Update: Don't want to use static context here

sak
  • 1,230
  • 18
  • 37

3 Answers3

1

ViewModel and Repository pattern is way to go. You are doing async network call on Main thread, very bad idea. For learning purposes - here is how to get your code working:

replace:

myApplicationContext = context!!.applicationContext

with:

myApplicationContext = requireContext()

or better - get rid of this variable entirely and just use requireContext() instead.

esr
  • 161
  • 2
  • 5
  • requireContext() too crashes if i don't use the static context, please read the question again I have updated it. – sak Dec 21 '19 at 19:30
  • you have not pasted stacktrace. from what you are saying and way you code - it might crash for number of reasons :) one of them could be using onViewCreated instead onActivityCreated. – esr Dec 21 '19 at 20:07
0

try to use this

myApplicationContext: Context = this.context ?: return

then

  Toast.makeText(myApplicationContext, "Data Not Available!",Toast.LENGTH_LONG).show()

for more details, you can see this link

0

Toasts are usually applied to the activity rather than an generic context, and demanding the context via context!! should be avoided; it is optional for a reason. I would try the following after defining @string/data_not_available and @string/super_region_name_template in the string resource xml:

val body = response?.body()
if (body?.isNotEmpty() == true) {
    growth_spinner.adapter = GrowthSpinnerAdapter(body)
    Log.e(TAG, getString(R.string.super_region_name_template, body.get(0).nameValue)) // if applicable, use .first() over .get(0) 
} else {
    activity?.run {
        Toast.makeText(this, getString(R.string.data_not_available), Toast.LENGTH_LONG).show()
    }
}
buggily
  • 418
  • 2
  • 12