Kotlin Inner Class не может инициировать объект Session - PullRequest
0 голосов
/ 03 декабря 2018
    import android.content.Context
import android.graphics.Color
import android.net.Uri
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toolbar
import java.util.ArrayList
import com.salesrep.auxxa.alliontechnologies.auxxasr.R.id.viewPager

import android.graphics.drawable.GradientDrawable
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.util.Log
import com.salesrep.auxxa.alliontechnologies.auxxasr.utillities.Session
import org.json.JSONObject


class NewPaymentActivity : AppCompatActivity(),SummaryFragment.OnFragmentInteractionListener,ReceiptDetailsFragment.OnFragmentInteractionListener{

    internal lateinit var viewpageradapter: ViewPagerAdapter //Declare PagerAdapter

    private var tabLayout: TabLayout? = null
    var viewPager: ViewPager? = null
    var toolbar: Toolbar? = null
    var myPreference : Session? =null

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_new_payment)
        myPreference= Session(this)
        viewpageradapter= ViewPagerAdapter(supportFragmentManager)

        viewPager = findViewById(R.id.viewPager) as ViewPager
        setupViewPager(viewPager!!)

        tabLayout = findViewById(R.id.tab_layout) as TabLayout
        tabLayout!!.setupWithViewPager(viewPager)

//      tabLayout!!.setSelectedTabIndicatorColor(getResources().getColor(R.color.t));
        tabLayout!!.setSelectedTabIndicatorHeight(0)




        val headerView = (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
                .inflate(R.layout.custom_tabs_for_payments, null, false)

        val receiptDetails = headerView.findViewById(R.id.tb_receipt_details) as TextView
        val paymentDetails = headerView.findViewById(R.id.tb_payment_details) as TextView
        val invoiceDetails = headerView.findViewById(R.id.tb_invoice_details) as TextView
        val summary = headerView.findViewById(R.id.tb_summary) as TextView

        receiptDetails.setTextColor(resources.getColor(R.color.white))
        val drawable = receiptDetails.getBackground() as GradientDrawable
        drawable.setColor(resources.getColor(R.color.received_payments))

        paymentDetails.setTextColor(resources.getColor(R.color.main))
        val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
        drawablepaymentDetails.setColor(resources.getColor(R.color.white))

        invoiceDetails.setTextColor(resources.getColor(R.color.main))
        val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
        drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

        summary.setTextColor(resources.getColor(R.color.main))
        val summarydrawable = summary.getBackground() as GradientDrawable
        summarydrawable.setColor(resources.getColor(R.color.white))

        tabLayout!!.getTabAt(0)!!.setCustomView(receiptDetails)
        tabLayout!!.getTabAt(1)!!.setCustomView(paymentDetails)
        tabLayout!!.getTabAt(2)!!.setCustomView(invoiceDetails)
        tabLayout!!.getTabAt(3)!!.setCustomView(summary)



        tabLayout!!.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {

                if(tab!!.position==0)
                {
                    Log.e("tab","0")

                    receiptDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = receiptDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))
                }
                else if(tab!!.position==1 && myPreference!!.getReceiptStatus())
                {

                    Log.e("tab","1")
                    Log.e("stataus",myPreference!!.getReceiptStatus().toString())

                    paymentDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = paymentDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails= receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))


                }
                else if(tab!!.position==2)
                {
                    Log.e("tab","2")

                    invoiceDetails.setTextColor(resources.getColor(R.color.white))
                    val drawable = invoiceDetails.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails= receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    summary.setTextColor(resources.getColor(R.color.main))
                    val summarydrawable = summary.getBackground() as GradientDrawable
                    summarydrawable.setColor(resources.getColor(R.color.white))


                }
                else if(tab!!.position==3)
                {
                    Log.e("tab","3")

                    summary.setTextColor(resources.getColor(R.color.white))
                    val drawable = summary.getBackground() as GradientDrawable
                    drawable.setColor(resources.getColor(R.color.received_payments))

                    receiptDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablereceiptDetails = receiptDetails.getBackground() as GradientDrawable
                    drawablereceiptDetails.setColor(resources.getColor(R.color.white))

                    paymentDetails.setTextColor(resources.getColor(R.color.main))
                    val drawablepaymentDetails = paymentDetails.getBackground() as GradientDrawable
                    drawablepaymentDetails.setColor(resources.getColor(R.color.white))

                    invoiceDetails.setTextColor(resources.getColor(R.color.main))
                    val drawableinvoiceDetails = invoiceDetails.getBackground() as GradientDrawable
                    drawableinvoiceDetails.setColor(resources.getColor(R.color.white))
                }
                else {

                }

            }
            override fun onTabUnselected(tab:TabLayout.Tab?){
            }
            override fun onTabReselected(tab:TabLayout.Tab?) {
            }
        })


    }

    private fun setupViewPager(viewPager: ViewPager) {
        viewPager.setOffscreenPageLimit(-1);
        val adapter = ViewPagerAdapter(supportFragmentManager)
        viewPager.adapter = adapter



    }

   inner class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {



        override fun getItem(position: Int): Fragment? {
            var fragment: Fragment? = null

            if (position == 0 ) {
                Log.e("frag",position.toString())
                fragment = ReceiptDetailsFragment()
            } else if (position == 1 && myPreference!!.getReceiptStatus() ) {
                Log.e("frag",position.toString())
                fragment = PaymentDetailsFragment()
            } else if (position == 2) {
                Log.e("frag",position.toString())
                fragment = InvoiceDetailsFragment()
            } else if (position == 3) {
                Log.e("frag",position.toString())
                fragment = InvoiceDetailsFragment()
            }
            return fragment
        }

        override fun getPageTitle(position: Int): CharSequence {
            return when (position) {
                0 -> "Receipt Details"
                1 -> "Payment Details"
                2 -> "Invocie Details"
                3 -> "Summary"
                else -> throw IllegalArgumentException()
            }
        }

        override fun getCount(): Int {
            return 4
        }
    }

    override fun onFragmentInteraction(jsonObject: JSONObject) {
        //session intialization
        val myPreference = Session(this)
        myPreference.setJsonObject(jsonObject.toString())
        viewPager!!.setCurrentItem(1,true)


    }


    override fun onFragmentInteraction(uri: Uri) {

    }

}

private operator fun Int.invoke(i: Int) {

}

Выше я подключил свой класс NewPaymentActivity. Но проблема в том, что я получил одно исключение нулевого указателя после запуска этого кода. Мне нужно использовать значения сеанса внутри моего внутреннего класса. Но, похоже, проход инициализации сеансанулевое значениеВнутри внутреннего класса я использовал myPreference !!. GetReceiptStatus () , но значение myPreference равно null. Ниже я также подключу свою запись в журнале.

 Process: com.salesrep.auxxa.alliontechnologies.auxxasr, PID: 6082
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference

1 Ответ

0 голосов
/ 03 декабря 2018
myPreference!!.getReceiptStatus()

избегайте использования "!!", всегда проверяйте на обнуляемость,

myPreference?.let { it.getReceiptStatus() } 

используйте вот так, исключение будет решено

override fun onFragmentInteraction(jsonObject: JSONObject) {
    //session intialization
    val myPreference = Session(this)
    myPreference.setJsonObject(jsonObject.toString())
    viewPager!!.setCurrentItem(1,true)


}

здесь вы назначаетелокальная переменная myPreference, я думаю, вам может понадобиться изменить или присвоить ее глобальной переменной, просто удалите val из - val myPreference = Session (this)

...