0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

It's an age-old problem for all Java developers. Everyone's had this problem one time or another.
Ah, yes. When you search for problems which seem to be horribly complex you overlook the easiest possibility...many thanks.
@DaysShadow Don't forget to mark the answer as accepted. My apologies if it was not possible yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.