Получить ViewHolder из деятельности - PullRequest
0 голосов
/ 02 апреля 2020

Привет) Я новичок в Android dev. Я делаю приложение с контролем тестов.

Вот мое задание:

class TestActivity : AppCompatActivity() {

    private lateinit var urlToTest: String
    private val list = ArrayList<Test>()
    private var randomList = ArrayList<Test>()
    private var currentItem = 0
    private var fragmentsList = ArrayList<Fragment>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)

        val title = getIntent().getStringExtra("TestTitle")
        setTitle(title)

        urlToTest = "http://sasmobile.ru" + getIntent().getStringExtra("urlToJson") + getIntent().getStringExtra("jsonName")


        val recView = findViewById<RecyclerView>(R.id.testRecyclerView)
        recView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)

        val connector = Connector().isConnectedToNetwork(this)
        val submitButton : Button = findViewById(R.id.submitButton)

        if (connector) {
            AsyncTaskHandler().execute(urlToTest)

            submitButton.setOnClickListener{

                if (currentItem<9) {
                    currentItem += 1
                    testAdapterItemClick(randomList[currentItem], currentItem)
                }

                if (currentItem==9){
                    checkTest(randomList)
                }
            }
        }
        else{
            submitButton.visibility=View.INVISIBLE
            openAlertDialog()
        }


    }


    private fun openAlertDialog(){
        val dialogBuilder = AlertDialog.Builder(this)
        val connector = Connector().isConnectedToNetwork(this)

        dialogBuilder.setMessage("Check your Internet connection")
            .setCancelable(false)

            .setPositiveButton("Try again", DialogInterface.OnClickListener{
                    dialog, id -> if (connector) {
                dialog.cancel()
                AsyncTaskHandler().execute(urlToTest)
            }
            else openAlertDialog()
            })


        val alertBox = dialogBuilder.create()
        alertBox.setTitle("Ooops")
        alertBox.show()
    }



    private fun checkTest(testList: ArrayList<Test>){
        val recView : RecyclerView = findViewById(R.id.testRecyclerView)

        for (i in 0 until testList.size) {
            val viewHolder = recView.findViewHolderForAdapterPosition(i) as RecyclerView.ViewHolder
            val view = viewHolder.itemView

            val cardView = view.findViewById<CardView>(R.id.testCardView)

            if (testList[i].examination) {
                cardView.setCardBackgroundColor(getResources().getColor(R.color.colorTrue))
            }
            if (!testList[i].examination){
                cardView.setCardBackgroundColor(getResources().getColor(R.color.colorFalse))
            }
        }

    }



    private fun testAdapterItemClick(item: Test, currI : Int) {

        val fT: FragmentTransaction = supportFragmentManager.beginTransaction()

        currentItem = currI

        val recView : RecyclerView = findViewById(R.id.testRecyclerView)
        val layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
        layoutManager.scrollToPositionWithOffset(currentItem-3, 0)
        recView.layoutManager=layoutManager

        val submitButton : Button = findViewById(R.id.submitButton)
        if (currentItem<9){
            submitButton.text="Next Questions"
        }
        if (currentItem==9){
            submitButton.text="Finish Test"
        }



        if (item.typeQuestion == "input") {
            val bundle = Bundle()
            bundle.putParcelable("ITEM", item)

            if(!item.questionImageSrc.isNullOrEmpty())
                bundle.putString("IMAGE_KEY", item.questionImageSrc)

            fragmentsList[currentItem].setArguments(bundle)
            if (!fragmentsList[currentItem].isAdded())
                fT.add(R.id.frameLayout, fragmentsList[currentItem])
            if (fragmentsList[currentItem].isAdded())
                fT.replace(R.id.frameLayout, fragmentsList[currentItem])
        }


        if (item.typeQuestion == "singleChoice") {
            val bundle = Bundle()
            bundle.putParcelable("ITEM", item)

            val count = item.singleChoiceAnswers.count()
            bundle.putInt("COUNT_KEY", count)

            fragmentsList[currentItem].setArguments(bundle)

            if (!fragmentsList[currentItem].isAdded())
                fT.add(R.id.frameLayout, fragmentsList[currentItem])
            if (fragmentsList[currentItem].isAdded())
                fT.replace(R.id.frameLayout, fragmentsList[currentItem])
        }

        if (item.typeQuestion == "multipleChoice") {
            val bundle = Bundle()
            bundle.putParcelable("ITEM", item)

            val count = item.multipleChoiceAnswers.count()
            bundle.putInt("COUNT_KEY", count)

            fragmentsList[currentItem].setArguments(bundle)

            if (!fragmentsList[currentItem].isAdded())
                fT.add(R.id.frameLayout, fragmentsList[currentItem])
            if (fragmentsList[currentItem].isAdded())
                fT.replace(R.id.frameLayout, fragmentsList[currentItem])
        }

        fT.addToBackStack(null)
        fT.commit()

    }



    inner class AsyncTaskHandler() : AsyncTask<String, String, String>() {

        override fun onPreExecute() {
            val proggressBar: ProgressBar = findViewById(R.id.progressBarTest)
            proggressBar.visibility = View.VISIBLE
            super.onPreExecute()
        }


        override fun doInBackground(vararg params: String?): String {
            val res: String
            val connection = URL(urlToTest).openConnection() as HttpURLConnection

            try {
                connection.connect()
                res = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }
            } finally {
                connection.disconnect()
            }
            return res
        }


        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            if (progressBarTest.visibility == View.VISIBLE)
                progressBarTest.visibility = View.INVISIBLE
            jsonResult(result)
        }


        private fun jsonResult(jsonString: String?) {

            val jsonArray = JSONArray(jsonString)

            for (i in 0 until jsonArray.length()){
                val jsonObject = jsonArray.getJSONObject(i)
                val typeQuestion = jsonObject.getString("typeQuestion")

                val curentId = jsonObject.optInt("id")
                val curentNQ = jsonObject.optString("numberQuestion")
                val curentQ = jsonObject.optString("question")
                val curentQIS = jsonObject.optString("questionImageSrc")
                val curentEx = jsonObject.optBoolean("examination")


                if (typeQuestion.contains("multipleChoice")){
                    val multipleChoiceAnswers = jsonObject.getJSONArray("multipleChoiceAnswers")
                    val mlist = ArrayList<multipleChoiceAnswers>()
                    val ilist = ArrayList<inputAnswer>()
                    val slist = ArrayList<singleChoiceAnswer>()


                    for (sc in 0 until multipleChoiceAnswers.length()){
                        val curentMCA = multipleChoiceAnswers.getJSONObject(sc)
                        val letter = curentMCA.optString("letter")
                        val text = curentMCA.optString("text")
                        val correctAnswer = curentMCA.optBoolean("correctAnswer")
                        val checked = curentMCA.optBoolean("checked")

                        mlist.add(
                            multipleChoiceAnswers(
                                letter,
                                text,
                                correctAnswer,
                                checked
                            )
                        )
                    }
                    list.add(
                        Test(
                            curentId,
                            curentNQ,
                            curentQ,
                            curentQIS,
                            curentEx,
                            typeQuestion,
                            slist,
                            mlist,
                            ilist
                        )
                    )

                }
                if (typeQuestion.contains("singleChoice")){
                    val mlist = ArrayList<multipleChoiceAnswers>()
                    val ilist = ArrayList<inputAnswer>()
                    val slist = ArrayList<singleChoiceAnswer>()
                    val singleChoiceAnswer = jsonObject.getJSONArray("singleChoiceAnswers")

                    for (sc in 0 until singleChoiceAnswer.length()){
                        val curentSCA = singleChoiceAnswer.getJSONObject(sc)
                        val letter = curentSCA.optString("letter")
                        val text = curentSCA.optString("text")
                        val correctAnswer = curentSCA.optBoolean("correctAnswer")
                        val checked = curentSCA.optBoolean("checked")

                        slist.add(
                            singleChoiceAnswer(
                                letter,
                                text,
                                correctAnswer,
                                checked
                            )
                        )
                    }

                    list.add(
                        Test(
                            curentId,
                            curentNQ,
                            curentQ,
                            curentQIS,
                            curentEx,
                            typeQuestion,
                            slist,
                            mlist,
                            ilist
                        )
                    )

                }
                if (typeQuestion.contains("input")){
                    val inputAnswer = jsonObject.getJSONArray("inputAnswer")
                    val mlist = ArrayList<multipleChoiceAnswers>()
                    val ilist = ArrayList<inputAnswer>()
                    val slist = ArrayList<singleChoiceAnswer>()

                    for (sc in 0 until inputAnswer.length()){
                        val curentIA = inputAnswer.getJSONObject(sc)
                        val correctAnswer = curentIA.optString("correctAnswer")
                        val userAnswer = curentIA.optString("userAnswer")

                        ilist.add(
                            inputAnswer(
                                correctAnswer,
                                userAnswer
                            )
                        )
                    }
                    list.add(
                        Test(
                            curentId,
                            curentNQ,
                            curentQ,
                            curentQIS,
                            curentEx,
                            typeQuestion,
                            slist,
                            mlist,
                            ilist
                        )
                    )
                }


            }

            randomList = SubmitTest().getRandomList(list)

            fragmentsList= SubmitTest().getFragmentList(randomList)

            val adapter =
                TestAdapter(randomList) { item, position ->
                    testAdapterItemClick(item, position)
                }

            testAdapterItemClick(randomList[currentItem], currentItem)

            val recView = findViewById<RecyclerView>(R.id.testRecyclerView)

            recView.adapter = adapter

        }

    }

}

Я получаю тестовые вопросы от JSON я получаю 10 случайных вопросов и только помещаю их в RecyclerView.

это мой адаптер:

class TestAdapter(val test : ArrayList<Test>, private val testAdapterCallback: (Test, Int)-> Unit) : RecyclerView.Adapter<TestAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {

        val v = LayoutInflater.from(parent.context).inflate(R.layout.test_view_item, parent, false)


        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return test.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val num : Test = test[position]
        holder.textView.text = num.id.toString()

        holder.cardView.setOnClickListener(){
            testAdapterCallback(num, position)
        }
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

        val cardView = itemView.findViewById<CardView>(R.id.testCardView)
        val textView = itemView.findViewById<TextView>(R.id.testTextView)

    }

}

Я должен изменить цвет каждого вида карты в конце теста (зеленый, если он правильный, красный, если нет). Как я могу получить ViewHolder из действия и изменить цвет?

Я делаю это так:

private fun checkTest(testList: ArrayList<Test>){
        val recView : RecyclerView = findViewById(R.id.testRecyclerView)

        for (i in 0 until testList.size) {
            val viewHolder = recView.findViewHolderForAdapterPosition(i) as RecyclerView.ViewHolder
            val view = viewHolder.itemView

            val cardView = view.findViewById<CardView>(R.id.testCardView)

            if (testList[i].examination) {
                cardView.setCardBackgroundColor(getResources().getColor(R.color.colorTrue))
            }
            if (!testList[i].examination){
                cardView.setCardBackgroundColor(getResources().getColor(R.color.colorFalse))
            }
        }

    }

Но есть ошибка

kotlin.TypeCastException: null cannot be cast to non-null type androidx.recyclerview.widget.RecyclerView.ViewHolder

Заранее спасибо )

PS Извините за мой Engli sh)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...