Array Creation in Kotlin : No value passed for Parameter array [init]

Asked

Viewed 198 times

-1

kotlin array

Converti um código de java para kotlin, porém está com um erro que não consigo resolver

Here is the java code

public class IntroActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private Button btnNext;
    private ImageView[] vectorImage;
    private LinearLayout containerDots;
    private Drawable active;
    private Drawable inactive;
    private SliderFragmentAdapter adapterFragment;
    private int lengthSlide;
    private Button btnSkip;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro);
        initViews();
        configSlideAdapter();
        configNextSlideButton();
        configVetorImgSlid();
        configSkipOnboardingButton();
    }

    private void configSkipOnboardingButton() {
        btnSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finishOnboardin();
            }
        });
    }

    private void finishOnboardin() {
        finish();
        Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
        startActivity(intent);
    }

    private void configVetorImgSlid() {
        lengthSlide = adapterFragment.getCount();
        vectorImage = new ImageView[lengthSlide];
        prepareDots();
    }

    private void prepareDots() {
        for (int i = 0; i < lengthSlide; i++) {
            vectorImage[i] = new ImageView(this);
            vectorImage[i].setImageDrawable(inactive);

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.setMargins(16, 0, 16, 0);
            containerDots.addView(vectorImage[i], layoutParams);
        }
        vectorImage[0].setImageDrawable(active);
    }


    private void configSlideAdapter() {
        adapterFragment = new SliderFragmentAdapter(getSupportFragmentManager(), 4);
        viewPager.setAdapter(adapterFragment);
        viewPager.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < lengthSlide; i++) {
                    vectorImage[i].setImageDrawable(inactive);
                }
                vectorImage[position].setImageDrawable(active);
            }
            @Override
            public void onPageScrollStateChanged(int state) {}
        });
    }

    private void initViews() {
        viewPager = findViewById(R.id.viewPage);
        btnNext = findViewById(R.id.btn_next);
        containerDots = findViewById(R.id.container_dots);
        active = ContextCompat.getDrawable(this, R.drawable.active_dot);
        inactive = ContextCompat.getDrawable(this, R.drawable.inactive_dots);
        btnSkip = findViewById(R.id.btn_skip);
    }
    private void configNextSlideButton() {
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentSlide = viewPager.getCurrentItem();
                viewPager.setCurrentItem(currentSlide + 1);
                if (currentSlide == (lengthSlide - 1)) {
                    finishOnboardin();
                }
            }
        });
    }

}

Código em Kotlin Converted stays this way

import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import br.com.brq.brqmotors.onboarding.Adapter.ViewPagerAdapter


class OnboardingActivity : AppCompatActivity() {

    private var viewPager: ViewPager? = null
    private var btnNext: Button? = null
    private var vectorImage: Array<ImageView>? = null
    private var containerDots: LinearLayout? = null
    private var active: Drawable? = null
    private var inactive: Drawable? = null
    private var adapterFragment: ViewPagerAdapter? = null
    private var lengthSlide: Int = 0
    private var btnSkip: Button? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(br.com.brq.brqmotors.R.layout.activity_onboarding)
        initViews()
        configSlideAdapter()
        configNextSlideButton()
        configVetorImgSlid()
        configSkipOnboardingButton()
    }

    private fun configSkipOnboardingButton() {
        btnSkip!!.setOnClickListener { finishOnboarding() }
    }

    private fun finishOnboarding() {
        finish()
        val intent = Intent(applicationContext, javaClass::class.java)
        startActivity(intent)
    }

private fun configVetorImgSlid() {
    lengthSlide = adapterFragment.getCount()
    vectorImage = arrayOfNulls<ImageView>(lengthSlide)
    prepareDots()
}

private fun prepareDots() {
        for (i in 0 until lengthSlide) {
            vectorImage?.set(i, ImageView(this))
            vectorImage!![i].setImageDrawable(inactive)

            val layoutParams = LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.setMargins(16, 0, 16, 0)
            containerDots!!.addView(vectorImage!![i], layoutParams)
        }
        vectorImage!![0].setImageDrawable(active)
    }


    private fun configSlideAdapter() {
        adapterFragment = ViewPagerAdapter(supportFragmentManager, 4)
        viewPager!!.adapter = adapterFragment
        viewPager!!.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                for (i in 0 until lengthSlide) {
                    vectorImage!![i].setImageDrawable(inactive)
                }
                vectorImage!![position].setImageDrawable(active)
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    private fun initViews() {
        viewPager = findViewById(br.com.brq.brqmotors.R.id.viewPagerPrincipal)
        btnNext = findViewById(br.com.brq.brqmotors.R.id.btn_proximo)
        containerDots = findViewById(br.com.brq.brqmotors.R.id.container_pontos)
        btnSkip = findViewById(br.com.brq.brqmotors.R.id.btn_pular)
    }

    private fun configNextSlideButton() {
        btnNext!!.setOnClickListener(View.OnClickListener {
            val currentSlide = viewPager!!.currentItem
            viewPager!!.currentItem = currentSlide + 1
            if (currentSlide == lengthSlide - 1) {
                finishOnboarding()
            }
        })
    }

}

The error is found here

 private fun configVetorImgSlid() {
    lengthSlide = adapterFragment.getCount()
    vectorImage = arrayOfNulls<ImageView>(lengthSlide)
    prepareDots()
}

1 answer

1

The excerpt is in error because vectorImage was declared as Array<ImageView>?, meaning that the value of the variable can be null (for example, it may or may not have an array there) but the contents of the array cannot contain null, so if an array is in the variable, none of them can be null and when you try to assign arrayOfNulls<ImageView>(lengthSlide) to it, you are passing an array of size lengthSlide which accepts null in content and is fully filled with null.

Some possible statements, are not all possibilities but already gives an idea:

var vectorImage: Array<ImageView>? = null // Pode ser nula mas o conteúdo não. Iniciada nula
var vectorImage: Array<ImageView?>? = null // Pode ser nula e o conteúdo também. Iniciada nula
var vectorImage: Array<ImageView> // Não pode ser nula e nem seu conteúdo. Tem que iniciar no init
var vectorImage: Array<ImageView?> // Não pode ser nula mas seu conteúdo pode. Tem que iniciar no init
var vectorImage = emptyArray<ImageView>() // Não pode ser nula e nem seu conteúdo. Iniciada vazia
var vectorImage = emptyArray<ImageView?>() // Não pode ser nula mas seu conteúdo pode. Iniciada vazia

You can also mark the variable as lateinit to tell Kotlin that it will start null but then it will receive a non-null value and will never be null again. If something tries to access it before it is started, an Exception will be fired (although it starts null, it will never return null)

// Não pode ser nula mas seu conteúdo pode. Iniciada quando quiser.
lateinit var vectorImage: Array<ImageView?> 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.