IAmTheSquidward
IAmTheSquidward

Reputation: 582

Randomly set background image - Android

I have a background set on a login screen, and I want to randomly set the background every time the app is loaded from a pile of images in my drawables folder. However, my app crashes with every attempt at writing code to do this.

I have my array defined in layout/strings.xml:

<?xml version="1.0" encoding="utf-8"?>

<string name="app_name">MyFSU</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>

<style name="DefaultButtonText">
    <item name="android:layout_width">fill_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#979797</item>
    <item name="android:gravity">center</item>
    <item name="android:layout_margin">3dp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textSize">20sp</item>
    <item name="android:shadowColor">#f9f9f9</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">1</item>
</style>

<array name="myImages">
   <item>@drawable/a</item>
   <item>@drawable/b</item>
   <item>@drawable/c</item>
   <item>@drawable/d</item>
   <item>@drawable/e</item>
</array>

And then here's my code to actually generate a random image:

public class MainActivity extends ActionBarActivity {

final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);
final Random random = new Random();

public void backgrounds(View v) {
    int randomInt = random.nextInt(myImages.length());
    int drawableID = myImages.getResourceId(randomInt, -1);
    background.setBackgroundResource(drawableID);
}

Logcat is showing a null pointer exception at <init>, but I have no clue where that is or how to fix it. :(

Does anyone have any suggestions?

Upvotes: 1

Views: 3802

Answers (2)

Blackbelt
Blackbelt

Reputation: 157457

You should move

final RelativeLayout background = (RelativeLayout) findViewById(R.id.back);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.myImages);

inside onCreate, after setContentView. setContentView(int), inflate and place the inflated view inside the Activity view's hierarchy, allowing you to look for R.id.back, in your case, inside it

Upvotes: 2

erik
erik

Reputation: 4958

i would make a method that takes a min and max value:

pseudo code

public static int generateRandomInt(int min,int max)
    {
        return min + (int)(Math.random() * ((max - min) + 1));
    }

public void backgrounds(View v) {
    int randomInt = generateRandomInt(0,myImages.length()-1);
    int drawableID = myImages.getResourceId(randomInt);
    v.setBackgroundResource(getResources().getDrawable(drawableID)); // assuming your array is of resource ids
}

Upvotes: 0

Related Questions