Android Studio Convert Java To Kotlin 2 errors - android

After Convert Java File to Kotlin File, gives me two errors in same line: In code below show variables and function with error
lateinit var ncArr: Array<ImageButton>
lateinit var xBitmap: Bitmap
lateinit var oBitmap: Bitmap
lateinit var intArr: IntArray
lateinit var btnStartGame: Button
lateinit var btnMenu: Button
var stop: Boolean = false
var gameMode: Int = 0
var umove: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onStart()
setContentView(R.layout.activity_game)
ncArr = arrayOfNulls(9)
ncArr[0] = findViewById(R.id.nc0) as ImageButton
ncArr[1] = findViewById(R.id.nc1) as ImageButton
ncArr[2] = findViewById(R.id.nc2) as ImageButton
ncArr[3] = findViewById(R.id.nc3) as ImageButton
ncArr[4] = findViewById(R.id.nc4) as ImageButton
ncArr[5] = findViewById(R.id.nc5) as ImageButton
ncArr[6] = findViewById(R.id.nc6) as ImageButton
ncArr[7] = findViewById(R.id.nc7) as ImageButton
ncArr[8] = findViewById(R.id.nc8) as ImageButton
ncArr[0].setOnClickListener(this)
ncArr[1].setOnClickListener(this)
ncArr[2].setOnClickListener(this)
ncArr[3].setOnClickListener(this)
ncArr[4].setOnClickListener(this)
ncArr[5].setOnClickListener(this)
ncArr[6].setOnClickListener(this)
ncArr[7].setOnClickListener(this)
ncArr[8].setOnClickListener(this)
xBitmap = BitmapFactory.decodeResource(resources, R.drawable.x)
oBitmap = BitmapFactory.decodeResource(resources, R.drawable.o)
intArr = IntArray(9)
for (i in 0..8) {
intArr[i] = 0
}
btnMenu = findViewById(R.id.btnMenu) as Button
btnStartGame = findViewById(R.id.btnStartGame) as Button
btnMenu.setOnClickListener(this)
btnStartGame.setOnClickListener(this)
stop = false
gameMode = intent.getIntExtra("game_mode", 1)
umove = 1
}
in line ncArr = arrayOfNulls(9)
There are errors:
I trying to fix this problem but i don't have more ideas...
Any sollution?
thanks in advance

ncArr = arrayOfNulls(9)
The type of ncArr will be Array<ImageButton?>
ncArr[0] = findViewById(R.id.nc0) as ImageButton
You are using unsafe cast operator as, because the cast operator throws an exception if the cast is not possible. Thus, we call it unsafe. What happens if
findViewById(R.id.nc0) as ImageButton
return null, then null cannot assign to ImageButton, it will throw an exception and make your app crash.
To avoid the above error you can use
ncArr[0] = findViewById(R.id.nc0) as ImageButton?
or using safe cast operator as?
ncArr[0] = findViewById(R.id.nc0) as? ImageButton
Remember apply for ncArr[0] to ncArr[8].
Update: Based on your request, you can use this solution:
lateinit var ncArr: Array<ImageButton>
lateinit var xBitmap: Bitmap
lateinit var oBitmap: Bitmap
lateinit var intArr: IntArray
lateinit var btnStartGame: Button
lateinit var btnMenu: Button
var stop: Boolean = false
var gameMode: Int = 0
var umove: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onStart()
setContentView(R.layout.activity_game)
ncArr = arrayOf(
findViewById<ImageButton>(R.id.nc0).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc1).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc2).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc3).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc4).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc5).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc6).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc7).apply{setOnClickListener(this#GameActivity)},
findViewById<ImageButton>(R.id.nc8).apply{setOnClickListener(this#GameActivity)}
)
xBitmap = BitmapFactory.decodeResource(resources, R.drawable.x)
oBitmap = BitmapFactory.decodeResource(resources, R.drawable.o)
// Your code here
...
}

You trying to put Nullable array into NonNull. You may declare intArr as Array<ImageButton?> and everything will work.

Related

Cannot multiply variables?

So I'm trying to learn Kotlin and i'm a few days in. I am trying to build a Coin Calculator app that will take input of quantity of each type of coin you have and then using a class value it will add up all your change and tell you a total. I apologize for not being able to be too specific other than my error: None of the following functions can be called with the arguments supplied:
public final operator fun times(other: Byte): Double defined in kotlin.Double
public final operator fun times(other: Double): Double defined in kotlin.Double
it's showing these on my quarter total and dime total variables.
As I said I am new and actively studying looking for insight on what I am doing wrong, also any other advice over my messy coding that you see would be greatly appreciated.
-Thanks!
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//MyCode
val submitButton: Button = findViewById(R.id.submit)
var quarterQuan: EditText = findViewById(R.id.quarterInput)
var dimeQuan: EditText = findViewById(R.id.dimeInput)
submitButton.setOnClickListener{
val dime = Dime()
val quarter= Quarter()
var quarterTotal: Float = quarter.quarterVal*quarterQuan
var dimeTotal: Float = dime.dimeVal*dimeQuan
var cashTotal: Float = dimeTotal + quarterTotal
val resultTextViewLabel: TextView = findViewById(R.id.textResult)
resultTextViewLabel.text = cashTotal.toString()
}
}
}
class Quarter(){
val quarterVal = 0.25
}
class Dime(){
val dimeVal = 0.10
}
quarterQuan and dimeQuan are of type EditText (they are not numbers) and cannot be multiplied with a Float.
What you need to do is to read the values of these EditTexts:
val quarterEditTextValue = quarterQuan.text.toString().toFloat()
val dimeEditTextValue = dimeQuan.text.toString().toFloat()
You can then use these values for multiplication
var quarterTotal = quarter.quarterVal*quarterEditTextValue
var dimeTotal = dime.dimeVal*dimeEditTextValue
Have to add that you need to make each initial EditText value to be 0.0 to avoid NumberFormatException.
<EditText
android:id="#+id/quarterInput"
android:text="0.0" .... />

Android/Kotlin: Intent always NULL

I have searched through multiple posts on here which seem to all have the same problem but with different causes. I am getting NULL results from my bundle when calling them from the second activity. I will post more of my code if required;
Here is where i package my bundle on initial activity:
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
And when I am in my second activity:
val bundle :Bundle ?=intent.extras
val difficultystring = bundle?.getString("EXTRA_DIFFICULTY")
val catstring = bundle?.getString("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your cat is " + catstring
In both cases it return null. The spinners initialise on create so there should always be a value to call, can anyone point me in the right direction please?
FULL CODE (less functions - not causing any issues)
Activity 1
class MainActivity : AppCompatActivity() {
lateinit var btnSTART: Button
lateinit var switchSNOW: Switch
lateinit var imageviewSNOW: ImageView
lateinit var requested_difficulty: String
lateinit var dif_spinner: Spinner
lateinit var cat_spinner: Spinner
var difficulty_array = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dif_spinner = findViewById(R.id.difficulty_spinner)
cat_spinner = findViewById(R.id.cat_spinner)
switchSNOW = findViewById(R.id.snow_switch) as Switch
imageviewSNOW = findViewById(R.id.imageViewSnow) as ImageView
imageviewSNOW.setVisibility(View.INVISIBLE);
switchSNOW.setOnCheckedChangeListener { _, isChecked ->
if(isChecked){
imageviewSNOW.setVisibility(View.VISIBLE);
} else {
imageviewSNOW.setVisibility(View.INVISIBLE);
}
}
btnSTART = findViewById(R.id.buttonSTART) as Button
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
startActivity(intent)
}
// Create an ArrayAdapter using the string array and a default spinner layout
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.difficulty_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
dif_spinner.adapter = adapter
}
ArrayAdapter.createFromResource(
this,
R.array.cat_array,
android.R.layout.simple_spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
cat_spinner.adapter = adapter
}
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
}
}
Activity 2
class Quiz : AppCompatActivity() {
lateinit var txtV: TextView
lateinit var btn1: Button
lateinit var btn2: Button
lateinit var btn3: Button
lateinit var btn4: Button
lateinit var viewQ: TextView
var ans: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz)
btn1 = findViewById(R.id.button1) as Button
btn2 = findViewById(R.id.button2) as Button
btn3 = findViewById(R.id.button3) as Button
btn4 = findViewById(R.id.button4) as Button
viewQ = findViewById(R.id.textview_question)
txtV = findViewById(R.id.textView_info) as TextView
ans = GetQuestion(1, rand(1, 6))
btn1.setOnClickListener{
val theirans: String = btn1.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn1.setBackgroundResource(R.color.lime_green);
} else {
btn1.setBackgroundResource(R.color.red);
}
next()
};
btn2.setOnClickListener {
val theirans: String = btn2.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn2.setBackgroundResource(R.color.lime_green);
} else {
btn2.setBackgroundResource(R.color.red);
}
next()
};
btn3.setOnClickListener{
val theirans: String = btn3.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn3.setBackgroundResource(R.color.lime_green);
} else {
btn3.setBackgroundResource(R.color.red);
}
next()
};
btn4.setOnClickListener{
val theirans: String = btn4.getText().toString() //this will get a string
val TheirAnswer = theirans.toInt() //this will get a no from the string
if(TheirAnswer==ans) {
btn4.setBackgroundResource(R.color.lime_green);
} else {
btn4.setBackgroundResource(R.color.red);
}
next()
};
val bundle :Bundle ?=intent.extras
val difficultystring = bundle?.getString("EXTRA_DIFFICULTY")
val catstring = bundle?.getString("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your category is " + catstring
}
Use below answer
val intent = intent
val difficultystring = intent.getStringExtra("EXTRA_DIFFICULTY")
val catstring = intent.getStringExtra("EXTRA_CAT")
txtV.text = "Your difficulty level is " + difficultystring + " and your cat is " + catstring
Question raised by #cutiko provided the answer to my problem. For some reason I added the bundle to the end of my code rather than with my start activity intent.
From activity 1 my code went from:
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
startActivity(intent)
}
&
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
to
btnSTART.setOnClickListener{
val intent = Intent(this, Quiz::class.java)
val extras = Bundle()
extras.putString("EXTRA_DIFFICULTY", dif_spinner.getSelectedItem().toString())
extras.putString("EXTRA_CAT", cat_spinner.getSelectedItem().toString())
intent.putExtras(extras)
startActivity(intent)
}

Create a 2d Array for a maze game with Kotlin

So i have a Class called Cell and i want to create a matrix of objects Cell but im stuck and lost, this is what i got so far and its not working
How do i do this the right way? thanks
class GameView(context: Context?, attrs: AttributeSet?) :
View(context, attrs) {
private val COLS:Int = 7
private val ROWS: Int = 10
fun createMaze(){
//this gives me an error Type inference failed. Expected type
//mismatch:
//required:
//Array<Array<Cell>>
//found:
//Array<IntArray>
var cells: Array<Array<Cell>> = Array(COLS, {IntArray(ROWS)})
for(x in 0..COLS){
for(y in 0..ROWS){
cells[x][y] = Cell(x,y)
}
}
}
}
class Cell(var col:Int, var row: Int){
var topWall = true
var leftWall = true
var bottomWall = true
var rightWall = true
}
You defined your cells type as Array<Array<Cell>>, but initialized as Array<IntArry>
I think there is just a small change:
class Cell(var col:Int=0, var row: Int=0){
var topWall = true
var leftWall = true
var bottomWall = true
var rightWall = true
}
var cells: Array<Array<Cell>> = Array(COLS, {Array<Cell>(ROWS, {Cell()})})

Function to animate an ImageView in a RecyclerView

To forward my application, i need a function that will rotate an imageView in a recyclerView.
The recyclerView is one of 3 recyclerviews that are already working well, and are clickable through a cardView.
shortvideo there:
https://mega.nz/#!W6AyAYaY!07WG8kr_POYiGsgt0yja6fk8RaclZLw2-MiMFrmEQmk
I created Classes with a few members, which permit to know the state of the objects.
I am newbie in Android programmation, and it was difficult for me to make these recyclerView working well :-)
7 April : i finally succeeded to implement my function
but the result is weird !
can see there :
https://mega.nz/#!DzI2iaiB!VBG9Ex4TZlAsoUYPSRhXXMP4weH-9hXyjbqF1nCRyeA
There is an imageView which is rotating, but this is the left one, not the clicked one, and there is a mix, a swap between pictures.
My question is : are the imageViews clickable and focusable like cardViews ?
if so i can try to make the imageView focusable and clickable (actually the cardView is... )
What about the index is recyclerViews ? isn't it the cardview which is clicked which has the index ? or the left one in the screen ?
I am puzzled :-)
Following: the layout with CardView and imageView; MainActivity where i tried to write the function; and the Adapter for the Top RecyclerView where the function is supposed to
rotate (180 °) the imageView at the index ( index, tag and position )
no change about that xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.cardview.widget.CardView
android:id="#+id/flag_card_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ImageView
android:id="#+id/flagcountry"
android:layout_width="0dp"
android:layout_height="match_parent"
app:layout_constraintDimensionRatio="W,55:100"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginLeft="2dp"/>
<TextView
android:id="#+id/flagname"
android:layout_width="6dp"
android:layout_height="match_parent"
app:layout_constraintLeft_toRightOf="#id/flagcountry"
android:layout_centerVertical="true"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
under new kt file
package training.geography.triplerecyclerview
import android.provider.Settings.Global.getString
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
class FlagAdapter(val flagcountrylist: List<FlagCard>,
val flagitemClickListener : View.OnClickListener
//val flagitemOnLongClickListener : View.OnLongClickListener
):
RecyclerView.Adapter<FlagAdapter.FlagViewHolder> () {
class FlagViewHolder(flagView: View) : RecyclerView.ViewHolder(flagView) {
val flagcardView = flagView.findViewById<CardView>(R.id.flag_card_view)
val flagcountry = flagView.findViewById<ImageView>(R.id.flagcountry)
val flagname = flagView.findViewById<TextView>(R.id.flagname)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
FlagViewHolder {
val inflater = LayoutInflater.from(parent.context)
val viewItem = inflater.inflate(R.layout.item_flag, parent, false)
return FlagViewHolder(viewItem)
}
override fun onBindViewHolder(flagholder: FlagViewHolder, position: Int) {
//val flagcountry: String = flagcountrylist.FlagCard.flagimage[position]
//var flagimageList: List<String> = flagcountrylist.map { it.flagimage }
var flagsouthList: List<String> = flagcountrylist.map { it.flagsouth }
var iflagsouth = flagsouthList[position]
flagholder.flagname.text = iflagsouth
flagholder.flagcardView.tag = position
flagholder.flagcardView.setOnClickListener(flagitemClickListener)
//flagholder.flagcardView.setOnLongClickListener(itemOnLongClickListener)
when (position){
0 -> flagholder.flagcountry.setImageResource(R.drawable.afgcol)
1 -> flagholder.flagcountry.setImageResource(R.drawable.argsvk)
2 -> flagholder.flagcountry.setImageResource(R.drawable.armche)
3 -> flagholder.flagcountry.setImageResource(R.drawable.auttgo)
4 -> flagholder.flagcountry.setImageResource(R.drawable.azepry)
5 -> flagholder.flagcountry.setImageResource(R.drawable.bhrtur)
6 -> flagholder.flagcountry.setImageResource(R.drawable.bratls)
7 -> flagholder.flagcountry.setImageResource(R.drawable.bwasur)
8 -> flagholder.flagcountry.setImageResource(R.drawable.cafbtn)
9 -> flagholder.flagcountry.setImageResource(R.drawable.critun)
10 -> flagholder.flagcountry.setImageResource(R.drawable.pandza)
11 -> flagholder.flagcountry.setImageResource(R.drawable.persau)
12 -> flagholder.flagcountry.setImageResource(R.drawable.svnago)
13 -> flagholder.flagcountry.setImageResource(R.drawable.sweben)
14 -> flagholder.flagcountry.setImageResource(R.drawable.tcdgbr)
15 -> flagholder.flagcountry.setImageResource(R.drawable.thabol)
16 -> flagholder.flagcountry.setImageResource(R.drawable.tjkdeu)
17 -> flagholder.flagcountry.setImageResource(R.drawable.tkmbel)
18 -> flagholder.flagcountry.setImageResource(R.drawable.tzablz)
19 -> flagholder.flagcountry.setImageResource(R.drawable.ukrcmr)
20 -> flagholder.flagcountry.setImageResource(R.drawable.uryblr)
21 -> flagholder.flagcountry.setImageResource(R.drawable.venbgd)
22 -> flagholder.flagcountry.setImageResource(R.drawable.vnmbfa)
23 -> flagholder.flagcountry.setImageResource(R.drawable.yembih)
24 -> flagholder.flagcountry.setImageResource(R.drawable.zmbchl)
25 -> flagholder.flagcountry.setImageResource(R.drawable.zwealb)
}
//var iflagcard:String = imagelist[position]
//holder.flagcountry.setImageResource(iflagcard)
}
override fun getItemCount(): Int {
return flagcountrylist.size
}
}
---------------------------------------
//under new MainActivity file with function modified
// i don't know what to do with the variable
// flagtempup, i use it to set the string in
// iflagtrigramdown, and i have te warning variable not used...
package training.geography.triplerecyclerview
import android.nfc.Tag
import android.os.Bundle
import android.view.View
import android.view.View.OnClickListener
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_flag.*
data class FlagCard(var flagtrigramup: String, var flagtrigramdown: String,
var flagimage: String, var flagsouth: String, var rotationpossible: Boolean=(true))
data class CountryCard(val countrytrigram: String, val description: String)
data class MapCard(var map_left_up: String,
var map_right_up: String,
var map_left_down: String,
var map_right_down: String,
var maps_img: String,
var mapnorth: String)
class MainActivity : AppCompatActivity(), OnClickListener {
var afg_col = FlagCard("col", "afg", "afgcol", "afg", true)
var arg_svk = FlagCard("arg", "svk", "argsvk", "svk", true)
var arm_che = FlagCard("che", "arm", "armche", "arm", true)
var aut_tgo = FlagCard("tgo", "aut", "auttgo", "aut", true)
var aze_pry = FlagCard("aze", "pry", "azepry", "pry", true)
var bhr_tur = FlagCard("tur", "bhr", "bhrtur", "bhr", true)
var bra_tls = FlagCard("tls", "bra", "bratls", "bra", true)
var bwa_sur = FlagCard("sur", "bwa", "bwasur", "bwa", true)
var caf_btn = FlagCard("btn", "caf", "cafbtn", "caf", true)
var cri_tun = FlagCard("cri", "tun", "critun", "tun", true)
var pan_dza = FlagCard("pan", "dza", "pandza", "dza", true)
var per_sau = FlagCard("per", "sau", "persau", "sau", true)
var svn_ago = FlagCard("svn", "ago", "svnago", "ago", true)
var swe_ben = FlagCard("swe", "ben", "sweben", "ben", true)
var tcd_gbr = FlagCard("tcd", "gbr", "tcdgbr", "gbr", true)
var tha_bol = FlagCard("tha", "bol", "thabol", "bol", true)
var tjk_deu = FlagCard("tjk", "deu", "tjkdeu", "deu", true)
var tkm_bel = FlagCard("tkm", "bel", "tkmbel", "bel", true)
var tza_blz = FlagCard("tza", "blz", "tzablz", "blz", true)
var ukr_cmr = FlagCard("ukr", "cmr", "ukrcmr", "cmr", true)
var ury_blr = FlagCard("ury", "blr", "uryblr", "blr", true)
var ven_bgd = FlagCard("ven", "bgd", "venbgd", "bgd", true)
var vnm_bfa = FlagCard("vnm", "bfa", "vnmbfa", "bfa", true)
var yem_bih = FlagCard("yem", "bih", "yembih", "bih", true)
var zmb_chl = FlagCard("zmb", "chl", "zmbchl", "chl", true)
var zwe_alb = FlagCard("zwe", "alb", "zwealb", "alb", true)
var afg = CountryCard("afg", "afg")
var ago = CountryCard("ago", "ago")
var alb = CountryCard("alb", "alb")
var arg = CountryCard("arg", "arg")
var arm = CountryCard("arm", "arm")
var aut = CountryCard("aut", "aut")
var aze = CountryCard("aze", "aze")
var bel = CountryCard("bel", "bel")
var bfa = CountryCard("bfa", "bfa")
var bhr = CountryCard("bhr", "bhr")
var bih = CountryCard("bih", "bih")
var blz = CountryCard("blz", "blz")
var bol = CountryCard("bol", "bol")
var bra = CountryCard("bra", "bra")
var btn = CountryCard("btn", "btn")
var bwa = CountryCard("bwa", "bwa")
var caf = CountryCard("caf", "caf")
var che = CountryCard("che", "che")
var chl = CountryCard("chl", "chl")
var cmr = CountryCard("cmr", "cmr")
var col = CountryCard("col", "col")
var cri = CountryCard("cri", "cri")
var deu = CountryCard("deu", "deu")
var gbr = CountryCard("gbr", "gbr")
var pan = CountryCard("pan", "pan")
var per = CountryCard("per", "per")
var pry = CountryCard("pry", "pry")
var sau = CountryCard("sau", "sau")
var sur = CountryCard("sur", "sur")
var svk = CountryCard("svk", "svk")
var svn = CountryCard("svn", "svn")
var swe = CountryCard("swe", "swe")
var tcd = CountryCard("tcd", "tcd")
var tgo = CountryCard("tgo", "tgo")
var tha = CountryCard("tha", "tha")
var tjk = CountryCard("tjk", "tjk")
var tkm = CountryCard("tkm", "tkm")
var tls = CountryCard("tls", "tls")
var tun = CountryCard("tun", "tun")
var tur = CountryCard("tur", "tur")
var tza = CountryCard("tza", "tza")
var ukr = CountryCard("ukr", "ukr")
var ury = CountryCard("ury", "ury")
var ven = CountryCard("ven", "ven")
var vnm = CountryCard("vnm", "vnm")
var yem = CountryCard("yem", "yem")
var zmb = CountryCard("zmb", "zmb")
var zwe = CountryCard("zwe", "zwe")
var arm_bol_gbr_ago = MapCard("arm", "bol", "gbr", "ago", "bol", "armbolgbrago")
var aze_bra_aut_ben = MapCard("aze", "bra", "aut", "ben", "bra", "azebraautben")
var bfa_blr_col_bgd = MapCard("bfa", "blr", "col", "bgd", "blr", "bfablrcolbgd")
var bwa_bel_bhr_chl = MapCard("bwa", "bel", "bhr", "chl", "bel", "bwabelbhrchl")
var caf_afg_alb_arg = MapCard("caf", "afg", "alb", "arg", "afg", "cafafgalbarg")
var che_tkm_tur_sur = MapCard("che", "tkm", "tur", "sur", "tkm", "chetkmtursur")
var cri_cmr_btn_bih = MapCard("cri", "cmr", "btn", "bih", "cmr", "cricmrbtnbih")
var sau_blz_deu_dza = MapCard("sau", "blz", "deu", "dza", "blz", "saublzdeudza")
var svn_tha_tcd_pry = MapCard("svn", "tha", "tcd", "pry", "tha", "svnthatcdpry")
var swe_tls_tgo_per = MapCard("swe", "tls", "tgo", "per", "tls", "swetlstgoper")
var tjk_pan_svk_tza = MapCard("tjk", "pan", "svk", "tza", "pan", "tjkpansvktza")
var ven_zwl_yem_ukr = MapCard("ven", "zwl", "yem", "ukr", "zwl", "venzwlyemukr")
var zmb_tur_ury_vnm = MapCard("zmb", "tur", "ury", "vnm", "tur", "zmbtururyvnm")
var flagcountrylist = listOf<FlagCard>(
afg_col,
arg_svk,
arm_che,
aut_tgo,
aze_pry,
bhr_tur,
bra_tls,
bwa_sur,
caf_btn,
cri_tun,
pan_dza,
per_sau,
svn_ago,
swe_ben,
tcd_gbr,
tha_bol,
tjk_deu,
tkm_bel,
tza_blz,
ukr_cmr,
ury_blr,
ven_bgd,
vnm_bfa,
yem_bih,
zmb_chl,
zwe_alb
)
val flagadapter = FlagAdapter(flagcountrylist, this)
var countryList = listOf<CountryCard>(
afg,
ago,
alb,
arg,
arm,
aut,
aze,
bel,
bfa,
bhr,
bih,
blz,
blz,
bol,
bra,
btn,
bwa,
caf,
che,
chl,
cmr,
col,
cri,
deu,
gbr,
pan,
per,
pry,
sau,
sur,
svk,
svn,
swe,
tcd,
tgo,
tha,
tjk,
tkm,
tls,
tun,
tur,
tza,
ukr,
ury,
ven,
vnm,
yem,
zmb,
zwe
)
val countryadapter = CountryAdapter(countryList)
var mapcountrylist = listOf<MapCard>(
arm_bol_gbr_ago,
aze_bra_aut_ben,
bfa_blr_col_bgd,
bwa_bel_bhr_chl,
caf_afg_alb_arg,
che_tkm_tur_sur,
cri_cmr_btn_bih,
sau_blz_deu_dza,
svn_tha_tcd_pry,
swe_tls_tgo_per,
tjk_pan_svk_tza,
ven_zwl_yem_ukr,
zmb_tur_ury_vnm
)
val mapadapter = MapAdapter(mapcountrylist)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val flagsrecyclerView = findViewById<RecyclerView>(R.id.flagsRecyclerView)
flagsrecyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
flagsrecyclerView.adapter = flagadapter
val countryrecyclerView = findViewById<RecyclerView>(R.id.countriesRecyclerView)
countryrecyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
countryrecyclerView.adapter = countryadapter
val maprecyclerView = findViewById<RecyclerView>(R.id.mapsRecyclerView)
maprecyclerView.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false)
maprecyclerView.adapter = mapadapter
}
fun rotateFlagCard (flagCard: FlagCard, position: Int) : FlagCard {
var flagtrigramuplist: List<String> = flagcountrylist.map{it.flagtrigramup }
var iflagtrigramup : String = flagtrigramuplist[position]
var flagimagelist = flagcountrylist.map{it.flagimage}
var iflagimage = flagimagelist[position]
var flagsouthlist = flagcountrylist.map { it.flagsouth }
var iflagsouth = flagsouthlist[position]
var rotationpossiblelist : List<Boolean> = flagcountrylist.map{ it.rotationpossible }
var irotationpossible = rotationpossiblelist[position]
var iflagimageView = findViewById<ImageView>(R.id.flagcountry)
when (position) {
0 -> iflagimageView.setImageResource(R.drawable.afgcol)
1 -> iflagimageView.setImageResource(R.drawable.argsvk)
2 -> iflagimageView.setImageResource(R.drawable.armche)
3 -> iflagimageView.setImageResource(R.drawable.auttgo)
4 -> iflagimageView.setImageResource(R.drawable.azepry)
5 -> iflagimageView.setImageResource(R.drawable.bhrtur)
6 -> iflagimageView.setImageResource(R.drawable.bratls)
7 -> iflagimageView.setImageResource(R.drawable.bwasur)
8 -> iflagimageView.setImageResource(R.drawable.cafbtn)
9 -> iflagimageView.setImageResource(R.drawable.critun)
10 -> iflagimageView.setImageResource(R.drawable.pandza)
11 -> iflagimageView.setImageResource(R.drawable.persau)
12 -> iflagimageView.setImageResource(R.drawable.svnago)
13 -> iflagimageView.setImageResource(R.drawable.sweben)
14 -> iflagimageView.setImageResource(R.drawable.tcdgbr)
15 -> iflagimageView.setImageResource(R.drawable.thabol)
16 -> iflagimageView.setImageResource(R.drawable.tjkdeu)
17 -> iflagimageView.setImageResource(R.drawable.tkmbel)
18 -> iflagimageView.setImageResource(R.drawable.tzablz)
19 -> iflagimageView.setImageResource(R.drawable.ukrcmr)
20 -> iflagimageView.setImageResource(R.drawable.uryblr)
21 -> iflagimageView.setImageResource(R.drawable.venbgd)
22 -> iflagimageView.setImageResource(R.drawable.vnmbfa)
23 -> iflagimageView.setImageResource(R.drawable.yembih)
24 -> iflagimageView.setImageResource(R.drawable.zmbchl)
25 -> iflagimageView.setImageResource(R.drawable.zwealb)
else -> throw AssertionError()
}
if (irotationpossible)
{
iflagimageView.animate().apply {
rotationBy(180f)
duration = 1000L
start()
// permutation of values north south
var flagtrigramdownlist :List<String> = flagcountrylist.map{it.flagtrigramdown}
var iflagtrigramdown : String = flagtrigramdownlist[position]
var flagtempup: String = iflagtrigramup
var flagtempdown: String = iflagtrigramdown
iflagtrigramup = iflagsouth
//flagtempdown = flagtempup
iflagtrigramdown = flagtempup
var iflagCard = FlagCard( iflagtrigramup, iflagtrigramdown, iflagimage, iflagsouth, irotationpossible )
return iflagCard
}
} else {
return flagCard
//Toast.makeText(this, "flag already matched country", Toast.LENGTH_LONG).show()
}
}
override fun onClick(flagcardView: View) {
if (flagcardView.tag != null) {
val index = flagcardView.tag as Int
var flagsouthList: List<String> = flagcountrylist.map{it.flagsouth }
val flags = flagsouthList[index]
Toast.makeText(this, "country : ${flags}", Toast.LENGTH_LONG).show()
var flagcard:FlagCard = flagcountrylist[index]
rotateFlagCard (flagcard, index)
}
}
}
It looks like nobody is interested by what is possible to do with RecyclerViews...
I still have the problem that when an imageView is clicked, this is the one at left which is rotating ! i can't understand what happens, examination in debugger shows the variables are ok, the index is position and do not change...
I tried to apply rotate function to the cardView, same result !
I modified the code in the function and replace the flagCard by iflagCard if rotation was done (because two flags, one up, one down, and of course the FlagCard is different... )
Here the new code :
if (irotationpossible)
{
iflagcardView.animate().apply {
rotationBy(180f)
duration = 1000L
start()
// permutation of values north south
var flagtrigramdownlist :List<String> = flagcountrylist.map{it.flagtrigramdown}
var iflagtrigramdown : String = flagtrigramdownlist[position]
var flagtempup: String = iflagtrigramup
var flagtempdown: String = iflagtrigramdown
iflagtrigramup = iflagsouth
iflagsouth = flagtempup
iflagtrigramdown = flagtempup
var iflagCard = FlagCard( iflagtrigramup, iflagtrigramdown, iflagimage, iflagsouth, irotationpossible )
//flagcountrylist.toSet(position, iflagCard)
//abstract operator fun set(position: Int, iflagCard: FlagCard): FlagCard
flagcountrylist.removeAt(position)
flagcountrylist.add(position, iflagCard)
return iflagCard
}
} else {
return flagCard
//Toast.makeText(this, "flag already matched country", Toast.LENGTH_LONG).show()
}
my question is now about the set function for mutableListOf in Kotlin :
i tried to use " abstract operator fun set(index: Int, element: E): E "
but couldn't build because of abstract !
Is there any other way than my solution to remove then add at the same index ?
Is there any experimented developper curious about the strange rotation in that app ?
https://www.youtube.com/watch?v=d9o7fttLBxk
Why not the image with right index ?

Type mismatch in ArrayOfNulls with Kotlin

I got a problem when converting my java code to kotlin.
This line of code is what making me the problem
dots = arrayOfNulls<TextView>(layouts.size)
it said:
Type mismatch. Required: Array(TextView)? - Found: Array(TextView?)
Let you here the whole code and hope you can give me hand to figure out what's wrong.
class WelcomeActivity : AppCompatActivity() {
private var viewPager: ViewPager? = null
private var myViewPagerAdapter: MyViewPagerAdapter? = null
private var dotsLayout: LinearLayout? = null
private var dots: Array<TextView>? = null
private var layouts: IntArray? = null
private var btnSkip: Button? = null
private var btnNext: Button? = null
private var prefManager: PrefManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Checking for first time launch - before calling setContentView()
prefManager = PrefManager(this)
if (!prefManager!!.isFirstTimeLaunch) {
launchHomeScreen()
finish()
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}
setContentView(R.layout.welcomescreen)
viewPager = findViewById(R.id.view_pager) as ViewPager
dotsLayout = findViewById(R.id.layoutDots) as LinearLayout
btnSkip = findViewById(R.id.btn_skip) as Button
btnNext = findViewById(R.id.btn_next) as Button
// layouts of all welcome sliders
// add few more layouts if you want
layouts = intArrayOf(R.layout.welcomescreen_slide1, R.layout.welcomescreen_slide2, R.layout.welcomescreen_slide3, R.layout.welcomescreen_slide4)
// adding bottom dots
addBottomDots(0)
// making notification bar transparent
changeStatusBarColor()
myViewPagerAdapter = MyViewPagerAdapter()
viewPager!!.adapter = myViewPagerAdapter
viewPager!!.addOnPageChangeListener(viewPagerPageChangeListener)
btnSkip!!.setOnClickListener { launchHomeScreen() }
btnNext!!.setOnClickListener {
// checking for last page
// if last page home screen will be launched
val current = getItem(+1)
if (current < layouts!!.size) {
// move to next screen
viewPager!!.currentItem = current
} else {
launchHomeScreen()
}
}
}
private fun addBottomDots(currentPage: Int) {
dots = arrayOfNulls<TextView>(layouts.size)
val colorsActive = resources.getIntArray(R.array.array_dot_active)
val colorsInactive = resources.getIntArray(R.array.array_dot_inactive)
dotsLayout!!.removeAllViews()
for (i in dots!!.indices) {
dots[i] = TextView(this)
dots!![i].text = Html.fromHtml("•")
dots!![i].textSize = 35f
dots!![i].setTextColor(colorsInactive[currentPage])
dotsLayout!!.addView(dots!![i])
}
if (dots!!.size > 0)
dots!![currentPage].setTextColor(colorsActive[currentPage])
}
Thanks in advance.
[EDIT]: Also, I noticed an error in a for statement, here:
for (i in dots!!.indices) {
dots[i] = TextView(this)
dots!![i].text = Html.fromHtml("•")
dots!![i].textSize = 35f
dots!![i].setTextColor(colorsInactive[currentPage])
dotsLayout!!.addView(dots!![i])
}
First, in the first line said Unresolve reference indices; then in second line say that dots[i] cannot smart cast to 'Array?' because it's a mutable property and finally in the lines behind every dot before dots!![i] says "Only safe (?) or not-null asserted (!!.) calls are allowed on a nullable receiver of type TextView?
An array of nulls is basically an array with every element equal to null. That means that your variable's type must accept nulls as well. To accomplish this you need to change your variable type to Array<TextView?>?.
Use:
private lateinit var dots: Array<TextView?>
Instead of:
private var dots: Array<TextView>? = null

Categories

Resources