1

Hi so I released my app a few months ago and it all was working fine and to a degree it still does. On devices running lower than android 5 everything is fine. But I tested on a 5 device today and my if statements are not working. For example it marks every answer as incorrect yet on a lower device the correct incorrect answers is working as intended. I know my code works but I can't work out why it doesn't work on android 5. The only thing I can think of is that i've missed something out on my manifest.

EDIT: WORKING ANSWER allows compatibility between <=4.0 and 5.0=<:

 button.setOnClickListener(new OnClickListener(){

                    @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override
                    public void onClick(View arg0) {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                            if (Word1.getDrawable().getConstantState().equals(Word1.getResources().getDrawable( R.drawable.img1).getConstantState())}}

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {        
                             if  (Word1.getDrawable().getConstantState().equals(Word1.getContext().getDrawable( R.drawable.img1).getConstantState())}}  }); 
Phil3992
  • 1,059
  • 6
  • 21
  • 45

1 Answers1

2

You need to use .equals to compare the objects.

== check if it's the same object not if the objects hold the same value, more info here

Your code shoud look like:

if(Word1.getDrawable().getConstantState().equals(getResources().getDrawable( R.drawable.img9).getConstantState())
Community
  • 1
  • 1
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56
  • 1
    Are you sure you replaced ALL the == by equals? because normaly it shouldn't work when you compare with ==, maybe this was tolarated someway in earlier version and it's not anymore – liltof Dec 13 '14 at 23:02
  • Ok I have changed the == to .equals (i agree this is a better method) but the same problem persists. On my 5.0 devices the if simple goes straight to the fail. But when I test on my 4.0 devices it all works as planned like before. Any idea why an if statement would be ignored like this? – Phil3992 Dec 14 '14 at 17:32
  • @Phil3992 any reason you are comparing the `ConstantState` instead of the `Drawable` itself? – LordRaydenMK Dec 14 '14 at 20:00
  • 1
    While this wasn't the excat answer the .equals was a big help. The actual problem lies with .getResources this works for 4.0 but .getcontext is needed for 5.0 – Phil3992 Dec 18 '14 at 10:29
  • Found a solution that should work for all versions: https://stackoverflow.com/a/44633363/458365 – pablisco Jun 19 '17 at 15:11