I coded an activity that when user press only a button, the background would change randomly. I put background images in drawable file,and created a array of these images in value. Here is what i have got now:
final LinearLayout background = (LinearLayout)findViewById(R.id.back);
Button button = (Button)findViewById(R.id.button1);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
button.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random(myImages.length());
int b = r.nextInt();
background.setBackgroundResource(b);
}
});
and the array:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="image">
<item>@drawable/background</item>
<item>@drawable/background_blue</item>
<item>@drawable/background_pink</item>
<item>@drawable/background_orange</item>
</array>
</resources>
It seems nothing wrong, but every time I start the emulator to check out, it always show that the activity stopped
can any one tell me what is the problem of my code?? I will appreciate that!!!
TO:Ashok logcat show these error
E/AndroidRuntime(802): FATAL EXCEPTION: main E/AndroidRuntime(802):java.lang.ArrayIndexOutOfBoundsException:length=456;index=1647793160
E/AndroidRuntime(802): at android.content.res.TypedArray.getResourceId(TypedArray.java:570)
E/AndroidRuntime(802): at com.example.cathy.MainActivity$1.onClick(MainActivity.java:39)
E/AndroidRuntime(802): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(802): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(802): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(802): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(802): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(802): atandroid.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(802): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(802): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(802): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(802): atcom.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(802): at dalvik.system.NativeStart.main(Native Method)