Morv
Morv

Reputation: 45

Strange string array behaviour in Android/Java

i'm new to Android and Java but i've got some experience in programming.

When i want to start the following in Android, it will crash:

package org.ds.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class Test extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Toast.makeText( this, 
                getResources( ).getStringArray( R.array.test_array ).length, 
                Toast.LENGTH_SHORT ).show( );
    }
}

I don't know why the app crashes but the array is defined as a string-array in values/arrays.xml with 6 items. It is also everything correct in the R.java, the array is defined there.

When i do the following it works:

package org.ds.test;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class Test extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        int arr_length = getResources( ).getStringArray( R.array.test_array ).length;

        Toast.makeText( this, 
                "array has a length of " + arr_length + " " + getResources( ).getStringArray( R.array.test_array ).length, 
                Toast.LENGTH_SHORT ).show( );
    }
}

So why does it work when i first call the length into a variable and then additionally call the length like i wanted? Android level is 8/2.2 It doesn't make sense to me, so maybe one of you has a clue.

Upvotes: 0

Views: 597

Answers (1)

longhairedsi
longhairedsi

Reputation: 3136

You're passing a number(int) not a String as the text, this is one solution:

String.valueOf(getResources( ).getStringArray( R.array.test_array ).length)

Edit: Your second example works as you are casting the number to a String by appending it to the String "array has a length of ".

Upvotes: 1

Related Questions