java - Android: What's the best hierarchy for this app? -
i have imagebutton
, want image change every time onresume()
or oncreate()
called.
i have method changes image, called mupdatebackground
, i'm having trouble working out how structure hierarchy mupdatebackground
, (containing imagebutton
) can called onresume()
, oncreate()
.
if backgroundpic
true, , image selected randomly, if false r.drawable.bg0
used instead.
there separate settings activity manages whether backgroundpic
variable set true or false.
here's code far:
1 public class mainactivity extends activity { 2 public static imagebutton mgetclicktime; 3 @override 4 protected void onresume() { 5 super.onresume(); 6 //get shared preferences 7 msharedpreferences = getsharedpreferences(preferences_name, mode_private); 8 dp = msharedpreferences.getint("decimalplaces", 0); 9 length_setting = msharedpreferences.getint("msselector", 1); 10 backgroundpic = msharedpreferences.getboolean("backgroundpic", true); 11 //mupdatebackground(); 12 } 12 @override 13 protected void oncreate(bundle savedinstancestate) { 14 super.oncreate(savedinstancestate); 15 setcontentview(r.layout.activity_main); 16 17 //get shared preferences 18 msharedpreferences = getsharedpreferences(preferences_name, mode_private); 19 dp = msharedpreferences.getint("decimalplaces", 0); 20 length_setting = msharedpreferences.getint("msselector", 5); 21 mupdatebackground(); 22 mgetclicktime.setonclicklistener(new view.onclicklistener() { 23 mupdatebackground(); 24 } 25 } 26 } 27 public void mupdatebackground() { 28 if (backgroundpic) { 29 int[] imageids = { 30 r.drawable.bg1, 31 r.drawable.bg2, 32 r.drawable.bg3, 33 r.drawable.bg4, 34 35 }; 36 random generator = new random(); 37 randomimageid = imageids[generator.nextint(imageids.length)]; 38 log.d("1", "backgroundpic: "+randomimageid); 39 } 40 else { 41 randomimageid = r.drawable.bg0; 42 log.d("1", "backgroundpic: "+randomimageid); 43 } 44 mgetclicktime = (imagebutton) findviewbyid(r.id.clicker); 45 mgetclicktime.setimageresource(randomimageid); 46 }
the problem have if uncomment line 11 nullpointerexception. there better way should organise code?
you should check code if null before using it. don't check if imageids[] null before use , (its been awhile) want make sure mgetclicktime assigned findviewbyid. in onresume seems possible stuff can have gone out of memory. typically check see if need re-initialize variable in on resume when i've done android in past. i'm suggesting way debug , more robust.
Comments
Post a Comment