开发者

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.


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 ".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜