I'm creating a screen lock app, and faced notification able to drag down in the lock screen.
I've research it and found this solution to block the notification bar by using addView code below, but I cannot remove the view after user unlocked my app. Please advice how to remove the view.
I've try to use manager.removeView(view); in public void onDestroy() { but it crashed after run this code.
This is the error message
FATAL EXCEPTION: main
Process: com.mehuljoisar.lockscreen, PID: 10256
java.lang.IllegalArgumentException: View=android.view.View{42348cc0 V.ED.... ........ 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:373)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:302)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:79)
at com.mehuljoisar.lockscreen.LockScreenActivity.disablePullNotificationTouch(LockScreenActivity.java:261)
at com.mehuljoisar.lockscreen.LockScreenActivity.access$100(LockScreenActivity.java:24)
at com.mehuljoisar.lockscreen.LockScreenActivity$2.onClick(LockScreenActivity.java:113)
at android.view.View.performClick(View.java:4469)
at android.view.View$PerformClick.run(View.java:18788)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5347)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:835)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:651)
at dalvik.system.NativeStart.main(Native Method)
Where should I put the removeView code?
private void disablePullNotificationTouch(String gg) {
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
WindowManager.LayoutParams localLayoutParams = new WindowManager.LayoutParams();
localLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
localLayoutParams.gravity = Gravity.TOP; //make the line top
localLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
// this is to enable the notification to recieve touch events
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
// Draws over status bar
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
localLayoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
localLayoutParams.height = (int) (25 * getResources().getDisplayMetrics().scaledDensity);
localLayoutParams.format = PixelFormat.RGBX_8888;
View view = new View(this);
if(gg == "on") {
manager.addView(view, localLayoutParams);
}else {
manager.removeView(view);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
disablePullNotificationTouch("on");
}
#Override
public void onDestroy() {
super.onDestroy();
disablePullNotificationTouch("off");
}
You use
WindowManager manager = ((WindowManager) this.getSystemService(Context.WINDOW_SERVICE));
Not use
WindowManager manager = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE));
Try it!
Related
I have a floating widget (that draws over all the apps) that on long click (mouse hold) will show a relative layout (remove_relativelayout) from the bottom so that the user can close the widget and the service will be destroyed.
On most Samsung phones I get this crash:
Fatal Exception: java.lang.IllegalArgumentException: View=android.widget.RelativeLayout{762db5 G.E...... ......ID 0,0-160,160 #7f09022d app:id/remove_relativelayout} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:569)
at android.view.WindowManagerGlobal.updateViewLayout(WindowManagerGlobal.java:463)
at android.view.WindowManagerImpl.updateViewLayout(WindowManagerImpl.java:101)
at com.xxxx.dev.floatingwidget.services.FloatingWidgetServices.lambda$widgetLongClick$0(FloatingWidgetServices.java:20)
at com.xxxxx.dev.floatingwidget.services.FloatingWidgetServices.lambda$widgetLongClick$0$FloatingWidgetServices(FloatingWidgetServices.java)
at com.xxxxxx.dev.floatingwidget.services.-$$Lambda$FloatingWidgetServices$DhV3rKQxnQ9oEEnb70PNAJKR8NQ.onAnimationUpdate(-.java:4)
at android.animation.ValueAnimator.animateValue(ValueAnimator.java:1558)
at android.animation.ValueAnimator.animateBasedOnTime(ValueAnimator.java:1349)
at android.animation.ValueAnimator.doAnimationFrame(ValueAnimator.java:1481)
at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:994)
at android.view.Choreographer.doCallbacks(Choreographer.java:794)
at android.view.Choreographer.doFrame(Choreographer.java:725)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7857)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
Here is on start:
WindowManager.LayoutParams paramRemove = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
windowType,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT);
paramRemove.gravity = Gravity.TOP | Gravity.LEFT;
removeView.setVisibility(View.GONE);
removeImg = removeView.findViewById(R.id.remove_img);
windowManager.addView(removeView, paramRemove);
I think its coming from this function but I'm not sure:
private void widgetLongClick() {
GlobalFunctions.printLn(">>>>>>>>>>>>Into FloatingWidgetService.chathead_longclick() ");
WindowManager.LayoutParams param_remove = (WindowManager.LayoutParams) removeView.getLayoutParams();
int x_cord_remove = (szWindow.x - removeView.getWidth()) / 2;
int y_cord_remove = szWindow.y - (removeView.getHeight() + getStatusBarHeight());
param_remove.x = x_cord_remove;
param_remove.y = y_cord_remove;
ValueAnimator va = ValueAnimator.ofFloat(szWindow.y, y_cord_remove);
int mDuration = 100;
if(removeView.isAttachedToWindow()){
if(param_remove != null){
if(windowManager !=null){
va.setDuration(mDuration);
va.addUpdateListener(animation -> {
param_remove.y = Math.round((Float) animation.getAnimatedValue());
windowManager.updateViewLayout(removeView, param_remove);
});
va.start();
}
}
}
}
I would recommend you add this removable layout into your XML file and have it be View.GONE until you require it, this way you don't have to be worried about adding it programmatically and settings the correct layout parameters (this is probably what's failing in your current code).
Once you receive the longClick on the other View, you can toggle the removable layout to be View.VISIBLE and perhaps even add combine that with a quick animation to make it seem more 'friendly' to the user.
I find the solution for my problem,
the problem was that I'm closing the activity before the view is loaded,
so what I did is to wait for 1 sec before closing the activity,
using simply:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
//close the activity after 1 sec
}
},1000);
I'm working on a term project and I'm new to java and android app development. I have experience in other programming languages, though. I'm trying to reverse engineer an app to make it able to connect and send data via bluetooth. I want to make a list with all the available bluetooth devices, a button to turn on/off bluetooth, one for making the phone discoverable for other devices and another to search for unpaired devices. But every time I add an OnClickListener to the onCreate method, the app crashes before it opens. Could anyone help me out?
The source code for the app I am trying to modify can be found here:
https://github.com/pazaan/600SeriesAndroidUploader
Here is the part that seems to makes it crash:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
And here is all of OnCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
btnStartConnection = (Button) findViewById(R.id.btnStartConnection);
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//FUCKUP:
lvNewDevices.setOnItemClickListener(MainActivity.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
byte[] bytes = etSend.getText().toString().getBytes(Charset.defaultCharset());
mBluetoothConnection.write(bytes);
}
});
mRealm = Realm.getDefaultInstance();
RealmResults<PumpStatusEvent> data = mRealm.where(PumpStatusEvent.class)
.findAllSorted("eventDate", Sort.DESCENDING);
if (data.size() > 0)
dataStore.setLastPumpStatus(data.first());
setContentView(R.layout.activity_main);
PreferenceManager.getDefaultSharedPreferences(getBaseContext()).registerOnSharedPreferenceChangeListener(this);
prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
if (!prefs.getBoolean(getString(R.string.preference_eula_accepted), false)) {
stopCgmService();
}
// setup preferences
configurationStore.setPollInterval(Long.parseLong(prefs.getString("pollInterval", Long.toString(MedtronicCnlIntentService.POLL_PERIOD_MS))));
configurationStore.setLowBatteryPollInterval(Long.parseLong(prefs.getString("lowBatPollInterval", Long.toString(MedtronicCnlIntentService.LOW_BATTERY_POLL_PERIOD_MS))));
configurationStore.setReducePollOnPumpAway(prefs.getBoolean("doublePollOnPumpAway", false));
chartZoom = Integer.parseInt(prefs.getString("chartZoom", "3"));
configurationStore.setMmolxl(prefs.getBoolean("mmolxl", false));
configurationStore.setMmolxlDecimals(prefs.getBoolean("mmolDecimals", false));
// Disable battery optimization to avoid missing values on 6.0+
// taken from https://github.com/NightscoutFoundation/xDrip/blob/master/app/src/main/java/com/eveningoutpost/dexdrip/Home.java#L277L298
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String packageName = getPackageName();
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (!pm.isIgnoringBatteryOptimizations(packageName)) {
Log.d(TAG, "Requesting ignore battery optimization");
try {
// ignoring battery optimizations required for constant connection
// to peripheral device - eg CGM transmitter.
final Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.d(TAG, "Device does not appear to support battery optimization whitelisting!");
}
}
}
LocalBroadcastManager.getInstance(this).registerReceiver(
statusMessageReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_STATUS_MESSAGE));
LocalBroadcastManager.getInstance(this).registerReceiver(
new UpdatePumpReceiver(),
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_UPDATE_PUMP));
mEnableCgmService = Eula.show(this, prefs);
IntentFilter batteryIntentFilter = new IntentFilter();
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_LOW);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
batteryIntentFilter.addAction(Intent.ACTION_BATTERY_OKAY);
registerReceiver(batteryReceiver, batteryIntentFilter);
IntentFilter usbIntentFilter = new IntentFilter();
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
usbIntentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
usbIntentFilter.addAction(MedtronicCnlIntentService.Constants.ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, usbIntentFilter);
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_NO_USB_PERMISSION));
LocalBroadcastManager.getInstance(this).registerReceiver(
usbReceiver,
new IntentFilter(MedtronicCnlIntentService.Constants.ACTION_USB_REGISTER));
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setElevation(0);
getSupportActionBar().setTitle("Nightscout");
}
final PrimaryDrawerItem itemSettings = new PrimaryDrawerItem()
.withName("Settings")
.withIcon(GoogleMaterial.Icon.gmd_settings)
.withSelectable(false);
final PrimaryDrawerItem itemRegisterUsb = new PrimaryDrawerItem()
.withName("Registered devices")
.withIcon(GoogleMaterial.Icon.gmd_usb)
.withSelectable(false);
final PrimaryDrawerItem itemStopCollecting = new PrimaryDrawerItem()
.withName("Stop collecting data")
.withIcon(GoogleMaterial.Icon.gmd_power_settings_new)
.withSelectable(false);
final PrimaryDrawerItem itemGetNow = new PrimaryDrawerItem()
.withName("Read data now")
.withIcon(GoogleMaterial.Icon.gmd_refresh)
.withSelectable(false);
final PrimaryDrawerItem itemUpdateProfile = new PrimaryDrawerItem()
.withName("Update pump profile")
.withIcon(GoogleMaterial.Icon.gmd_insert_chart)
.withSelectable(false);
final PrimaryDrawerItem itemClearLog = new PrimaryDrawerItem()
.withName("Clear log")
.withIcon(GoogleMaterial.Icon.gmd_clear_all)
.withSelectable(false);
final PrimaryDrawerItem itemCheckForUpdate = new PrimaryDrawerItem()
.withName("Check for App update")
.withIcon(GoogleMaterial.Icon.gmd_update)
.withSelectable(false);
assert toolbar != null;
new DrawerBuilder()
.withActivity(this)
.withAccountHeader(new AccountHeaderBuilder()
.withActivity(this)
.withHeaderBackground(R.drawable.drawer_header)
.build()
)
.withTranslucentStatusBar(false)
.withToolbar(toolbar)
.withActionBarDrawerToggle(true)
.withSelectedItem(-1)
.addDrawerItems(
itemSettings,
//itemUpdateProfile, // TODO - re-add when we to add Basal Profile Upload
itemRegisterUsb,
itemCheckForUpdate,
itemClearLog,
itemGetNow,
itemStopCollecting
)
.withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
#Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
if (drawerItem.equals(itemSettings)) {
openSettings();
} else if (drawerItem.equals(itemRegisterUsb)) {
openUsbRegistration();
} else if (drawerItem.equals(itemStopCollecting)) {
mEnableCgmService = false;
stopCgmService();
finish();
} else if (drawerItem.equals(itemGetNow)) {
// It was triggered by user so start reading of data now and not based on last poll.
sendStatus("Requesting poll now...");
startCgmService(System.currentTimeMillis() + 1000);
} else if (drawerItem.equals(itemClearLog)) {
clearLogText();
} else if (drawerItem.equals(itemCheckForUpdate)) {
checkForUpdateNow();
}
return false;
}
})
.build();
mTextViewLog = (TextView) findViewById(R.id.textview_log);
mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setSmoothScrollingEnabled(true);
mChart = (GraphView) findViewById(R.id.chart);
// disable scrolling at the moment
mChart.getViewport().setScalable(false);
mChart.getViewport().setScrollable(false);
mChart.getViewport().setYAxisBoundsManual(true);
mChart.getViewport().setMinY(80);
mChart.getViewport().setMaxY(120);
mChart.getViewport().setXAxisBoundsManual(true);
final long now = System.currentTimeMillis(),
left = now - chartZoom * 60 * 60 * 1000;
mChart.getViewport().setMaxX(now);
mChart.getViewport().setMinX(left);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setOnXAxisBoundsChangedListener is n/a in this version
/*
mChart.getViewport().setOnXAxisBoundsChangedListener(new Viewport.OnXAxisBoundsChangedListener() {
#Override
public void onXAxisBoundsChanged(double minX, double maxX, Reason reason) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
hasZoomedChart = (rightX != maxX || rightX - chartZoom * 60 * 60 * 1000 != minX);
}
});
*/
mChart.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
if (!mChart.getSeries().isEmpty() && !mChart.getSeries().get(0).isEmpty()) {
double rightX = mChart.getSeries().get(0).getHighestValueX();
mChart.getViewport().setMaxX(rightX);
mChart.getViewport().setMinX(rightX - chartZoom * 60 * 60 * 1000);
}
hasZoomedChart = false;
return true;
}
});
mChart.getGridLabelRenderer().setNumHorizontalLabels(6);
// due to bug in GraphView v4.2.1 using setNumHorizontalLabels reverted to using v4.0.1 and setHumanRounding is n/a in this version
// mChart.getGridLabelRenderer().setHumanRounding(false);
mChart.getGridLabelRenderer().setLabelFormatter(
new DefaultLabelFormatter() {
DateFormat mFormat = new SimpleDateFormat("HH:mm", Locale.US); // 24 hour format forced to fix label overlap
#Override
public String formatLabel(double value, boolean isValueX) {
if (isValueX) {
return mFormat.format(new Date((long) value));
} else {
return MainActivity.strFormatSGV(value);
}
}
}
);
}
Here is the logcat output:
09-26 12:38:19.826 6324-6324/? I/art: Late-enabling -Xcheck:jni
09-26 12:38:20.157 6324-6324/info.nightscout.android E/Fabric: Failure onPreExecute()
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:219)
at com.crashlytics.android.core.CrashlyticsCore.onPreExecute(CrashlyticsCore.java:207)
at io.fabric.sdk.android.InitializationTask.onPreExecute(InitializationTask.java:44)
at io.fabric.sdk.android.services.concurrency.AsyncTask.executeOnExecutor(AsyncTask.java:611)
at io.fabric.sdk.android.services.concurrency.PriorityAsyncTask.executeOnExecutor(PriorityAsyncTask.java:43)
at io.fabric.sdk.android.Kit.initialize(Kit.java:69)
at io.fabric.sdk.android.Fabric.initializeKits(Fabric.java:440)
at io.fabric.sdk.android.Fabric.init(Fabric.java:384)
at io.fabric.sdk.android.Fabric.setFabric(Fabric.java:342)
at io.fabric.sdk.android.Fabric.with(Fabric.java:313)
at info.nightscout.android.UploaderApplication.onCreate(UploaderApplication.java:32)
at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1046)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5402)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1541)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
09-26 12:38:20.202 6324-6379/info.nightscout.android E/Fabric: Error dealing with settings
java.lang.IllegalArgumentException: Fabric could not be initialized, API key missing from AndroidManifest.xml. Add the following tag to your Application element
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
at io.fabric.sdk.android.services.common.ApiKey.logErrorOrThrowException(ApiKey.java:110)
at io.fabric.sdk.android.services.common.ApiKey.getValue(ApiKey.java:61)
at io.fabric.sdk.android.services.settings.Settings.initialize(Settings.java:78)
at io.fabric.sdk.android.Onboarding.retrieveSettingsData(Onboarding.java:124)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:99)
at io.fabric.sdk.android.Onboarding.doInBackground(Onboarding.java:45)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:63)
at io.fabric.sdk.android.InitializationTask.doInBackground(InitializationTask.java:28)
at io.fabric.sdk.android.services.concurrency.AsyncTask$2.call(AsyncTask.java:311)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
09-26 12:38:20.252 6324-6324/info.nightscout.android W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
09-26 12:38:20.349 6324-6324/info.nightscout.android I/MainActivity: onCreate called
09-26 12:38:20.652 6324-6324/info.nightscout.android D/AndroidRuntime: Shutting down VM
09-26 12:38:20.652 6324-6324/info.nightscout.android E/AndroidRuntime: FATAL EXCEPTION: main
Process: info.nightscout.android, PID: 6324
java.lang.RuntimeException: Unable to start activity ComponentInfo{info.nightscout.android/info.nightscout.android.medtronic.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at info.nightscout.android.medtronic.MainActivity.onCreate(MainActivity.java:349)
at android.app.Activity.performCreate(Activity.java:6672)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Move the code setContentView(R.layout.activity_main);
under the super.onCreate(savedInstanceState);
you are mapping the views before adding layout in your code.
your onCreate() should be
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate called");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Do mapping all views
Your Error log is showing you your solution. The project is using Fabric API. So naturally you need to add Fabric API key to your project.
Do as suggested in Error log. Add following line in Android Manifest.
<meta-data android:name="io.fabric.ApiKey" android:value="YOUR_API_KEY"/>
For your API key, make a project using Fabric account and get your API key.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm making an Android app, it should ask for arithmetic equations and check the answer. There should be different difficulty levels as well. My app crashes when choosing the difficulty level from AlertDialog. I have no errors in Android Studio.
Here is the code for choosing level:
public void onClick(View view) {
if(view.getId()==R.id.play_btn){
//play button
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose a level")
.setSingleChoiceItems(levelNames, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
//start gameplay
startPlay(which);
}
});
AlertDialog ad = builder.create();
ad.show();
}
private void startPlay(int chosenLevel){
//start gameplay
Intent playIntent = new Intent(this, PlayGame.class);
playIntent.putExtra("level", chosenLevel);
this.startActivity(playIntent);
}
Can someone help me understand why my app crashes?
Here is the log:
9758-9758/org.example.braintraining E/AndroidRuntime: FATAL EXCEPTION: main
Process: org.example.braintraining, PID: 9758
java.lang.RuntimeException: Unable to start activity ComponentInfo{org.example.braintraining/org.example.braintraining.PlayGame}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2693)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference
at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
at android.app.Activity.performCreate(Activity.java:6289)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2758)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5942)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Here is the code for onCreate method of PlayGame class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playgame);
gamePrefs = getSharedPreferences(GAME_PREFS, 0);
//text and image views
question = (TextView)findViewById(R.id.question);
answerTxt = (TextView)findViewById(R.id.answer);
response = (ImageView)findViewById(R.id.response);
scoreTxt = (TextView)findViewById(R.id.score);
//hide tick cross initially
response.setVisibility(View.INVISIBLE);
//number, enter and clear buttons
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
btn3 = (Button)findViewById(R.id.btn3);
btn4 = (Button)findViewById(R.id.btn4);
btn5 = (Button)findViewById(R.id.btn5);
btn6 = (Button)findViewById(R.id.btn6);
btn7 = (Button)findViewById(R.id.btn7);
btn8 = (Button)findViewById(R.id.btn8);
btn9 = (Button)findViewById(R.id.btn9);
btn0 = (Button)findViewById(R.id.btn0);
enterBtn = (Button)findViewById(R.id.enter);
clearBtn = (Button)findViewById(R.id.clear);
//listen for clicks
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
enterBtn.setOnClickListener(this);
clearBtn.setOnClickListener(this);
//get passed level number
if(savedInstanceState!=null){
//restore state
}
else{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) level = passedLevel;
level=savedInstanceState.getInt("level");
int exScore = savedInstanceState.getInt("score");
scoreTxt.setText("Score: "+exScore);
}
}
//initialize random
random = new Random();
//play
chooseQuestion();
}
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.os.Bundle.getInt(java.lang.String)' on a null object reference at org.example.braintraining.PlayGame.onCreate(PlayGame.java:104)
Either the code might be failing in two scenarios:
You are starting new activity by passing the playIntent. Please check the code in PlayGame.java, in onCreate() you should be getting the string value (level) from Intent rather than from Bundle, something like
String chosenLevel;
Intent i = this.getIntent();
if(i != null){
chosenLevel = i.getStringExtra("level");
}
2.if you are rotating the screen, once you are in the play game activity where you are not saving the required value before the activity is destroyed and trying to retrieve it back once the activity is recreated .
Solution would be to use the put methods to store values in onSaveInstanceState():
protected void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putString("value", chosenLevel);
}
And restore the value from Bundle in onCreate() or you can use onRestoreInstanceState(), which is called after onStart(), whereas onCreate() is called before onStart().:
public void onCreate(Bundle bundle) {
if (bundle!= null){
chosenValue = bundle.getString("value");
}
}
I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated
I have the following error when showing a PopupWindow.
The errors are triggered by the line:
checkInPopup.showAtLocation((ViewGroup) mapView.getParent(), Gravity.CENTER_HORIZONTAL, 0, 0);
mapView is a MapView and nothing is null.
The stacktrace:
01-08 18:00:09.402: E/AndroidRuntime(27768): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.ViewRootImpl.setView(ViewRootImpl.java:513)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.view.Window$LocalWindowManager.addView(Window.java:537)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.invokePopup(PopupWindow.java:988)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:845)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.widget.PopupWindow.showAtLocation(PopupWindow.java:809)
01-08 18:00:09.402: E/AndroidRuntime(27768): at com.geoloc.ActivityCheckIn.onCreate(ActivityCheckIn.java:50)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.app.Activity.performCreate(Activity.java:4465)
01-08 18:00:09.402: E/AndroidRuntime(27768): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
This is the code from my activity (that extends MapActivity)
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.checkin);
mapView = (MapView) findViewById(R.id.mapview);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
checkInPopup = new PopupWindow(inflater.inflate(CHECK_IN_POPUP_LAYOUT, null, false));
checkInPopup.setOutsideTouchable(true);
checkInPopup.setHeight(100);
checkInPopup.setWidth(200);
checkInPopup.showAtLocation((ViewGroup) mapView.getParent(), Gravity.CENTER_HORIZONTAL, 0, 0);
}
Thank you for sharing your thoughts
Same problem happened with me when I try to show a popup menu in an activity.
I also got the same exception but I encountered problems and resolved it by providing the right context.
// at this line
Dialog dialog = new Dialog(getApplicationContext());
Use
YourActivityName.this instead of getApplicationContext()
and yes it worked for me may it will help someone else.
you are showing your popup too early. You may post a delayed runnable for showatlocation in Onresume , Give it a try
Edit:
This post seems to have the same problem answered Problems creating a Popup Window in Android Activity
Use:
YourActivityName.this
Instead of:
getApplicationContext();
There are two scenarios when this exception could occur. One is mentioned by nandeesh. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/
Make sure you handle both of them
The correct way is to call popupwindow.show() at onWindowFocusChanged():
#Override
protected void onCreate(Bundle savedInstanceState) {
View view = LayoutInflater.from(mContext).inflate(R.layout.popup_window_layout, new LinearLayout(mContext), true);
popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(view);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
popupWindow.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
}
}
A popup's parent can't itself be a popup. Both of their parents must be the same. So, if you create a popup inside a popup, you must save the parent's popup and make it a parent.
here's an example
Try to show the pop like below
findViewById(R.id.main_layout).post(new Runnable() {
public void run() {
mPopupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
Button close = (Button) customView.findViewById(R.id.btn_ok);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPopupWindow.dismiss();
doOtherStuff();
}
});
}
});
use this method before show
public static ViewGroup getActivityFirstLayout(Context ctx)
{
return (ViewGroup)((ViewGroup) ActivityMaster.getActivity(ctx).findViewById(android.R.id.content)).getChildAt(0);
}
private boolean activityIsOk(Activity activity)
{
boolean s1 = !(activity == null || activity.isFinishing());
if(s1)
{
View v = LayoutMaster.getActivityFirstLayout(activity);
return v.isShown() && ViewCompat.isLaidOut(v);
}
return false;
}
Try to use it
LayoutInflater inflater = (LayoutInflater).getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflate.from(YourActivity.this).inflate(R.layout.yourLayout, null);
Following many hours of search and testing i found following solution(by implementing different SO solutions) here it what didn't failed in any case i was getting crash.
Runnable runnable = new Runnable() {
#Override
public void run() {
//displayPopup,progress dialog or what ever action. example
ProgressDialogBox.setProgressBar(Constants.LOADING,youractivityName.this);
}};
Where logcat is indicating the crash is happening.. start a runnable .in my case at receiving broadcast.
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!isFinishing()) {
new Handler().postAtTime(runnable,2000);
}
}
});
try to show popup like this
new Handler().postDelayed(new Runnable(){
public void run() {
popupWindow.showAtLocation(context.getWindow().getDecorView(), Gravity.CENTER,0,0);
}
}, 200L);