How to Set the Background Drawable of a Button Properly Android - android

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?

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));
}

Related

Failed to bind to the service

On the app launch, I need to check whether a new version is available on play store or not. To check I have implemented below code in Splash screen.
private void checkNewVersionAvailability() {
appUpdateManager = AppUpdateManagerFactory.create(getApplicationContext());
appUpdateInfo = appUpdateManager.getAppUpdateInfo();
appUpdateInfo.addOnCompleteListener(new OnCompleteListener<AppUpdateInfo>() {
#Override
public void onComplete(Task<AppUpdateInfo> task) {
if (task.isComplete()) {
if (task.getResult().updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE) {
checkVersion(task.getResult());
} else if (task.getResult().updateAvailability() == UpdateAvailability.UPDATE_NOT_AVAILABLE) {
if (StringUtils.isNullOrEmpty(ChevronApplication.deviceId)) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
RegsiterDeviceHandler handler = new RegsiterDeviceHandler(SplashScreen.this);
handler.registerDevice(false);
handler.showNextScreen();
}
}, SLEEP_TIME);
} else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new RegsiterDeviceHandler(SplashScreen.this).showNextScreen();
}
}, SLEEP_TIME);
}
}
}
}
});
During testing on the device, I didn't get the issue. These crash logs are I found from the Pre-launch report in Playstore.
> FATAL EXCEPTION: main
Process: com.mac.app, PID: 19641
com.google.android.play.core.tasks.RuntimeExecutionException: com.google.android.play.core.internal.aa: Failed to bind to the service.
at com.google.android.play.core.tasks.k.getResult(Unknown Source)
at com.chevronrenaissance.app.activity.SplashScreen$2.onComplete(SplashScreen.java:113)
at com.google.android.play.core.tasks.a.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5538)
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:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: com.google.android.play.core.internal.aa: Failed to bind to the service.
at com.google.android.play.core.internal.q.b(Unknown Source)
at com.google.android.play.core.internal.q.a(Unknown Source)
at com.google.android.play.core.internal.s.a(Unknown Source)
at com.google.android.play.core.internal.r.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
There seems to be an issue with Google Play Core library with Android Virtual Devices. I had to add a try/catch statement so the Pre-launch testing passes. I think you may have to wrap al your AppUpdateManager calls so the exception is catched.
I was running a very similar issue using the in-app review component. It turned out one of the emulators I was developing with had not been signed into a Google Play account. You may want to ensure your emulator is signed into Google Play.
You can check task.isSuccessful().
In this case, when the task is not successful, you can get the exception use method task.getException()
Most likely that the Emulator you are using do not contain Google Play at all.
If you are running it in a emulator and if emulator is not signed for Google play, it will show the error that "PID: [6084] AppUpdateService : Failed to bind to the service."

I got a super weird crash on Fabric onResume of my FragmentActivity, at the super.onResume()

What does this mean, and can be fixed somehow?
Not crashing in my code, but in the super of the FragmentActivity, I can't figure out what I am doing wrong:
Fatal Exception: java.lang.IllegalArgumentException
at android.os.Parcel.readException(Parcel.java:1688)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:5505)
at android.app.Activity.isTopOfTask(Activity.java:5983)
at android.app.Activity.onResume(Activity.java:1253)
at android.support.v4.app.FragmentActivity.onResume(FragmentActivity.java:485)
at nl.hgrams.passenger.activities.PSTimelineFragmentsActivity.onResume(PSTimelineFragmentsActivity.java:576)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1270)
at android.app.Activity.performResume(Activity.java:6788)
at android.app.ActivityThread.performNewIntents(ActivityThread.java:2844)
at android.app.ActivityThread.handleNewIntent(ActivityThread.java:2858)
at android.app.ActivityThread.-wrap15(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1575)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6186)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
This is my onResume():
#Override
protected void onResume() {
super.onResume();
registerReceiver(addedPitstopBroadcastReceiver,
new IntentFilter("addedPitstop"));
if (PSApplicationClass.getInstance().pref.getUserId(PSTimelineFragmentsActivity.this) != null) {
renewSettings();
PSApplicationClass.getInstance().pref.setIsBackground(this, false);
if (PSApplicationClass.getInstance().pref.isRefetchUser(PSTimelineFragmentsActivity.this)) {
PSApplicationClass.getInstance().pref.setRefetchUser(PSTimelineFragmentsActivity.this, false);
MyFirebaseInstanceIDService.changeFirebaseToken(PSTimelineFragmentsActivity.this);
}
}
}
But it directly crashed at onResume, so it didn't pass to the next line. Also tried to reproduce me, but could not.
The user had a: LG G-Pad 8.3

Listener won't work

I'm trying to set a Listener for my custom views that I put in a LinearLayout. Those views are created by code depending on a certain files or data, so I don't know the number of views there is. The OnClickListener is being set, but onClick() is never called:
#Override
protected void onResume() {
super.onResume();
try {
setupBackEnd();
} catch (IOException e) {
Toast.makeText(this, "Error Reading or Writing data in Storage, Try to restart the App", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Toast.makeText(DayActivity.this, "Child count: " + linearList.getChildCount(), Toast.LENGTH_SHORT).show();
for (int i = 0; i < linearList.getChildCount(); i++) {
linearList.getChildAt(i).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(DayActivity.this, "clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
This is my code. To make sure the child views are already there I showed a Toast and it gave me "Child Count: 5" but "clicked" Toast never shows up. I made sure that My custom Views are clickable (The childs of linearlist). But the listener won't work for some reason. Anyone knows why?
Edit: After I tried to debug the code I got this error:
10-27 18:52:26.309 17630-17630/osm_cave.timecave E/AndroidRuntime: FATAL EXCEPTION: main
Process: osm_cave.timecave, PID: 17630
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#672721e is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:679)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.widget.Toast$TN.handleShow(Toast.java:459)
at android.widget.Toast$TN$2.handleMessage(Toast.java:342)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
c
This error won't be shown when I launch the app without debugging it only appears when Debugging with breakpoints. This error is supposed to mean I'm trying to use a context that no longer exist but I'm not so what's the problem here??
It looks like your toast message is running into an error.
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.widget.Toast$TN.handleShow(Toast.java:459)
at android.widget.Toast$TN$2.handleMessage(Toast.java:342)
at android.os.Handler.dispatchMessage(Handler.java:102)
If I remember correctly, the new object that you are creating of type View.OnClickListener (since it is anonymous) cannot access the DayActivity.this attribute. Instead you should get the activity from the view.
public void onClick(View view) {
Activity activity = (Activity) view.getContext()
Toast.makeText(activity, "clicked", Toast.LENGTH_SHORT).show();
}
While there's nothing wrong with using a Toast message to test for an event occurring, I would recommend simplifying to just using a log message. Log messages aren't context sensitive are unlikely to fail except if you provide a null message to it.
If Log messages are not working, the next troubleshooting step should be to examine the custom views and view hierarchy. If any clickable transparent views are in front of the custom views, they would intercept the click events. Double check that the view itself is clickable as well.

FlashLight App Fail to connect to camera service

Here Is my Code:
I have Added a github Permission code But it still Crashes
I have done every thing but it crashes Every Time
I also have added Permission for Camera in my manifest
parameter = camera.getParameters();
}
#Override public void onPermissionDenied(PermissionDeniedResponse response) {
Toast.makeText(getApplicationContext(), "Permission Denied", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("App needs permission to access camera")
.setPositiveButton("Granted", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent myAppSettings = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + getPackageName()));
myAppSettings.addCategory(Intent.CATEGORY_DEFAULT);
myAppSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(myAppSettings);
}
}).setNegativeButton("Denied", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
}).create().show();
}
#Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token)
{[enter image description here][1]
token.continuePermissionRequest();
}
}).check();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
textview = (TextView) findViewById(R.id.textView);
flashLight = (ImageButton) findViewById(R.id.flash_light);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//askPermission(CAMERA,camera1);
flashLight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isFlashLightOn) {
turnOnTheFlash();
} else {
turnOffTheFlash();
}
}
});
logCat:
09-30 18:59:31.698 11339-11339/inducesmile.com.androidflashlightapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: inducesmile.com.androidflashlightapp, PID: 11339
java.lang.RuntimeException: Unable to resume activity {inducesmile.com.androidflashlightapp/inducesmile.com.androidflashlightapp.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3506)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
at android.os.Handler.dispatchMessage(Handler.java:110)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934)
Caused by: java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.(Camera.java:647)
at android.hardware.Camera.open(Camera.java:510)
at inducesmile.com.androidflashlightapp.MainActivity.turnOffTheFlash(MainActivity.java:105)
at inducesmile.com.androidflashlightapp.MainActivity.onResume(MainActivity.java:165)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
at android.app.Activity.performResume(Activity.java:6791)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3477)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3546) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2795) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527) 
at android.os.Handler.dispatchMessage(Handler.java:110) 
at android.os.Looper.loop(Looper.java:203) 
at android.app.ActivityThread.main(ActivityThread.java:6251) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1073) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:934) 
09-30 18:59:31.804 11339-11347/inducesmile.com.androidflashlightapp I/art: Enter while loop.
I also had created a flashlight sensor based app a few months back. I have created gist for the code of the flashlight activity (both java and xml) and it seems to be working fine. Take a look at the below links and see if it helps:
https://gist.github.com/robillo/b27d37be3262164ee7f5532230c28c5a
https://gist.github.com/robillo/71afef65923138ed9d6011e3bd216249
Also, try doing your processing part of the activity in the if block in onCreate() like:
askForPermissions();
if(checkForPermission()){
//Do your processing here
}
The functions are:
void askForPermissions(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
getActivity().requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
}
boolean checkForPermission(){
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
It's tough to tell without seeing your turnOnTheFlash and turnOffTheFlash functions, but I'd guess that you are not properly releasing the camera at some point as shown by the documentation.

How to secure pre marshmallow application crashings

I am making an application that contains a part of activities that can be executed on pre marshmallow devices and some part of activities on marshmallow and above.
So what I want to do is don't let the application crash on pre marshmallow device that runs the activity that is supported on marshmallow device and just show a toast that your device does not support this module to access.
Here I am stuck on finger print module that crashes the applications on pre marshmallow device.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//do something
}
else
showToastMessage();
Error
FATAL EXCEPTION: main
java.lang.VerifyError: com/example/android/fingerprintdialog/MainActivity
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1130)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
at android.app.ActivityThread.access$700(ActivityThread.java:159)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
In my application I have a download button that requires runtime permission.
This is how I managed to do it:
public static int MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE = 1;
btnDownLoad.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
urlFromDownload();
}
});
public void urlFromDownload() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(getActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_DOWNLOAD_IMAGE);
} else {
DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
// My AsyncTask has not started yet
Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
} else {
downloadwall.execute(imageUrl);
}
}
} else {
DowloadFileFromUrl downloadwall = new DowloadFileFromUrl();
if (downloadwall.getStatus() == AsyncTask.Status.RUNNING) {
// My AsyncTask has not started yet
Toast.makeText(getActivity(), "Please wait until download is complete", Toast.LENGTH_SHORT).show();
} else {
downloadwall.execute(imageUrl);
}
}
}
I hope you understand my code. What I've done is wrote my download code twice. First for marshmallow and second for lower versions.
Just check whether installed app is using marshmallow or above Android OS.
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M)
{
// FingerPrint is supported by Android
// Show the FingerPrint touch screen.
}
else
{
//FingerPrint is not supported by Android
//Don't show the FingerPrint touch screen.
}
Put that within the below condition
if (Build.VERSION.SDK_INT >= 23) {
// Your code for
} else {
// Code for previous versions
}

Categories

Resources