Reputation: 15
I am trying to change the background of a button when the user press it in the emulator everything works fine but on a real device the app crash. here is my code:
answerOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
answerOne.setBackgroundResource(R.drawable.button_background_green);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ValidateAnswer(current5,Answers_six[0]);
}
});
and the error in the log is:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nasrf.winners10, PID: 9715
android.content.res.Resources$NotFoundException: Resource ID #0x7f080060
at android.content.res.Resources.getValue(Resources.java:1416)
at android.content.res.Resources.getDrawable(Resources.java:861)
at android.content.Context.getDrawable(Context.java:402)
at android.view.View.setBackgroundResource(View.java:16423)
at android.support.v7.widget.AppCompatButton.setBackgroundResource(AppCompatButton.java:83)
at com.example.nasrf.winners10.Game.GameActivity$16.onClick(GameActivity.java:426)
at android.view.View.performClick(View.java:4802)
at android.view.View$PerformClick.run(View.java:20101)
at android.os.Handler.handleCallback(Handler.java:810)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:189)
at android.app.ActivityThread.main(ActivityThread.java:5529)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:956)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:751)
any help please?
Upvotes: 0
Views: 93
Reputation: 4344
Its happening due to the difference in the SDK of your emulator and real device.
You can check the sdk first and then set the Background like this -
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
answerOne.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_background_green));
}
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
answerOne.setBackground(getResources().getDrawable(R.drawable.button_background_green));
} else{
answerOne.setBackground(ContextCompat.getDrawable(this, R.drawable.button_background_green));
}
Upvotes: 1