I am getting a window leak when I am starting a free walk activity. I have handled that scenario but still don't understand why I am still getting.
Here is my code:
private void showPopUp() {
final Dialog dialog = new Dialog(this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); //before
dialog.setContentView(R.layout.wwmove_screen_popup);
TextView mNo = (TextView) dialog.findViewById(R.id.move_no);
// if button is clicked, close the custom dialog
mNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
TextView mYes = (TextView) dialog.findViewById(R.id.moveyes);
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
startActivity(gotoSummary);
}
});
dialog.show();
}
The error I am getting is:
08-18 10:38:53.172 28118-28118/com.mobiefit.walk E/WindowManager: android.view.WindowLeaked: Activity com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{21f913f9 V.E..... R.....I. 0,0-960,516} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:364)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:274)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:298)
at com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity.showPopUp(WwFreeWalkMoveActivity.java:953)
at com.mobiefit.walk.freewalk.activity.WwFreeWalkMoveActivity.onOptionsItemSelected(WwFreeWalkMoveActivity.java:1806)
at android.app.Activity.onMenuItemSelected(Activity.java:2936)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:404)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:185)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:192)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19888)
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:5273)
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:908)
Can anyone tell me what I am doing wrong?
Window leaked exceptions are usually caused by dialogs which are not dismissed properly.
you have to dismiss the dialog
In your code
use this
dialog.dismiss();
mYes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
startActivity(gotoSummary);
}
});
Before proceeding to next activity or task. dismiss your dialog.dismiss(); dialog.
public void onClick(View v) {
killAll();
storeSegmentcompletdInformation("skipped");
storeOneDayInformation("skipped");
Intent gotoSummary = new Intent(WwFreeWalkMoveActivity.this, WwFreeWalkSummaryActivity.class);
gotoSummary.putExtra(ParamConstants.SUMMARY_GOOGLEFIT_KEY, String.valueOf(stepCountGoogleFit));
dialog.dismiss(); // here you just have to add one line.
startActivity(gotoSummary);
}
Related
I am working on an App that has a DialogBuilder Class where I implemented all the Dialogs for the App in order to be able to call them in other Services or Activities; that works very well except in one Activity, where I tried everything to pass the context - it is not working; hence, I would be more than delighted for any hints or help on this, thanks!
The Dialog:
public static void bookingConfirmationDialog(Context mContext) {
if(mContext != null) {
final Dialog dialog = new Dialog(GoldbekStorageApp.getInstance(), 0);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.new_booking_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
TextView textView = dialog.findViewById(R.id.messageId);
textView.setText(GoldbekStorageApp.getInstance().messageId);
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
The call of the Dialog:
proceedButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
message.setType(type);
message.setFromId(fromID);
message.setToId(toID);
message.setTypeId(typeID);
message.setTime(time);
message.setTitle(title);
message.setReceiptNo(receiptNo);
message.setNote(note);
RestClient.putBookingOnPallet(basic,message,context);
DialogBuilder.bookingConfirmationDialog(context);
/* Intent activityChangeIntent = new Intent( NewProductActivity.this,
NewProductActivity.class);
NewProductActivity.this.startActivity(activityChangeIntent);*/
}
});
I may be missing something but you could override onAttach in the DialogFragment class instead of passing the context in through the constructor.
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
I'm checking net connection, when internet is not available a custom dialog will appear and when net available again then it will disappear automatically, but when app is started and net is available already then it cause app crashing. how to fix it?
public class LoginActivity extends AppCompatActivity implements DroidListener{
private DroidNet mDroidNet;
MyDialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mDroidNet = DroidNet.getInstance();
mDroidNet.addInternetConnectivityListener(this);
//My custom dialog
myDialog = new MyDialog();
}
#Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
myDialog.dismiss();
} else {
myDialog.show(getSupportFragmentManager(), "my_dialog");
tv_check_connection.setText(R.string.no_connection);
tv_check_connection.setVisibility(View.VISIBLE);
connection.startAnimation(slideDownToUp);
connection.setBackgroundColor(Color.parseColor("#2D2D2D"));
tv_check_connection.setTextColor(Color.WHITE);
}
}
}
Here is my Dialog Fragment Class
public class MyDialog extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
Dialog dialog = new Dialog(getActivity(),R.style.myDialog);
final View view = getActivity().getLayoutInflater().inflate(R.layout.custom_dialog_nointernet, null);
dialog.getWindow().setContentView(view);
//dialog.getWindow().setBackgroundDrawable(d);
dialog.getWindow().setBackgroundDrawableResource(R.drawable.linearl_ayout_rounded_corner);
final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.CENTER;
dialog.setCanceledOnTouchOutside(true);
Button okay = (Button) view.findViewById(R.id.buttonOkay);
okay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return dialog;
}
}
Exception that I'm getting:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ritecare, PID: 2546
java.lang.IllegalStateException: Fragment MyDialog{51034a9 (967dd225-591f-4fb0-8a7d-a15846c04836)} not associated with a fragment manager.
at androidx.fragment.app.Fragment.requireFragmentManager(Fragment.java:910)
at androidx.fragment.app.DialogFragment.dismissInternal(DialogFragment.java:245)
at androidx.fragment.app.DialogFragment.dismiss(DialogFragment.java:202)
at com.example.ritecare.activities.LoginActivity.onInternetConnectivityChanged(LoginActivity.java:292)
at com.droidnet.DroidNet.publishInternetAvailabilityStatus(DroidNet.java:227)
at com.droidnet.DroidNet.access$100(DroidNet.java:34)
at com.droidnet.DroidNet$1.onTaskFinished(DroidNet.java:197)
at com.droidnet.DroidNet$1.onTaskFinished(DroidNet.java:193)
at com.droidnet.CheckInternetTask.onPostExecute(CheckInternetTask.java:76)
at com.droidnet.CheckInternetTask.onPostExecute(CheckInternetTask.java:33)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Put this check before you are dismissing your dialog.
if (isConnected) {
if (myDialog != null && myDialog.isShowing()) {
myDialog.dismiss();
}
} else {
// other code
myDialog.show(getSupportFragmentManager(), "my_dialog");
tv_check_connection.setText(R.string.no_connection);
tv_check_connection.setVisibility(View.VISIBLE);
connection.startAnimation(slideDownToUp);
connection.setBackgroundColor(Color.parseColor("#2D2D2D"));
tv_check_connection.setTextColor(Color.WHITE);
}
isShowing() method tells us Whether the dialog is currently showing or not. We are putting the check to dismiss the dialog only in the case when dialog is visible.
I ended up with this solution: (if you are using DialogFragment)
#Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
if (myDialog != null && myDialog.isAdded())
{
myDialog.dismiss();
}
} else {
myDialog.show(getSupportFragmentManager(), "my_dialog");
tv_check_connection.setText(R.string.no_connection);
tv_check_connection.setVisibility(View.VISIBLE);
connection.startAnimation(slideDownToUp);
connection.setBackgroundColor(Color.parseColor("#2D2D2D"));
tv_check_connection.setTextColor(Color.WHITE);
}
}
I have the following crash
java.lang.IllegalArgumentException: View=DecorView#62c59a[] not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:473)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:382)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:128)
at android.app.Dialog.dismissDialog(Dialog.java:727)
at android.app.Dialog.-android_app_Dialog-mthref-0(Dialog.java:167)
at android.app.Dialog$-void__init__android_content_Context_context_int_themeResId_boolean_createContextThemeWrapper_LambdaImpl0.run(Dialog.java)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6688)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1468)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1358)
can anyone please help and tell me what cause this crash and how to solve it ?
EDIT
this is the method that show the dialog
public static void showDialogMessage(Activity activity, String title,
String message, String buttonString, final OnClickListener listener) {
try {
final Dialog dialog = new Dialog(activity);
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_error_message_layout);
dialog.setCancelable(false);
TextView titleTV = (TextView) dialog.findViewById(R.id.title_textview);
TextView descriptionTV = (TextView) dialog
.findViewById(R.id.description_textview);
Button okButton = (Button) dialog.findViewById(R.id.ok_button);
Button cancelButton = (Button) dialog.findViewById(R.id.cancel_button);
titleTV.setText(title);
descriptionTV.setText(message);
okButton.setText(buttonString);
cancelButton.setVisibility(View.GONE);
okButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
if (listener != null)
listener.onClick(null);
}
});
dialog.getWindow().setBackgroundDrawableResource(
android.R.color.transparent);
dialog.show();
} catch (BadTokenException exception) {
exception.printStackTrace();
}
}
The error occurs when Activity gets finished before dialog successfully dismisses. So the Dialog's view is not attached to the windowManager.
Add this check before dismissing the Dialog:
if (!activity.this.isFinishing() && dialog != null) {
dialog.dismiss();
}
Alternatively you can dismiss your dialog in onPause() or onDestroy() of the activity.
#Override
public void onPause() {
super.onPause();
if ((dialog != null) && dialog.isShowing())
dialog.dismiss();
dialog = null;
}
I'm adding popup window in fragment when a user clicks on floating action button, in popup window I have added AutoComplete Edit field when I clicked the floating action button, the popup window shows successfully but when I click the edit field it gave an error.
The error is
Here is complete error.
Process: com.example.mubtadanaqvi.stunexus, PID: 7252
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#4234e238 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:769)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:278)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.widget.PopupWindow.invokePopup(PopupWindow.java:1067)
at android.widget.PopupWindow.showAsDropDown(PopupWindow.java:966)
at android.widget.ListPopupWindow.show(ListPopupWindow.java:635)
at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1119)
at android.widget.AutoCompleteTextView.updateDropDownForFilter(AutoCompleteTextView.java:973) at android.widget.AutoCompleteTextView.onFilterComplete(AutoCompleteTextView.java:955)
at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:285)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:548)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Here is my code
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View customView = inflater.inflate(R.layout.add_new_skill, null);
mPopupWindow = new PopupWindow(
customView,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
true
);
ImageButton cancel = (ImageButton) customView.findViewById(R.id.close_button);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mPopupWindow.dismiss();
}
});
skillListAdapter = new ArrayAdapter<>(getContext(),android.R.layout.simple_dropdown_item_1line, skillsList);
skillInputField = (AutoCompleteTextView) customView.findViewById(R.id.skill_input);
skillInputField.setThreshold(1);
skillInputField.setAdapter(skillListAdapter);
skillListAdapter.addAll(skillsList);
skillListAdapter.notifyDataSetChanged();
Button saveButton = (Button) customView.findViewById(R.id.save_skill);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String skillText = skillInputField.getText().toString();
if (skillText.isEmpty())
makeToast("EMPTY");
else {
if (ConnectivityListener.isNetwork(getContext())) {
// progressDialog.show();
mPopupWindow.dismiss();
makeToast(skillText);
list.add(new Skill_Item(skillText, 0));
adapter.notifyDataSetChanged();
} else
makeToast("connection error!");
}
}
});
mPopupWindow.showAtLocation(rootLayout, Gravity.CENTER, 0, 0);
}
});
Reason of Exception:
Activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.
Solution of Exception:
Please use isFinishing() method which is called by Android to check whether this activity is in the process of finishing:
private final WeakReference<MainActivity> mainActivityWeakRef;
mainActivityWeakRef =new WeakReference<MainActivity>(this);
if (mainActivityWeakRef.get() != null && !mainActivityWeakRef.get().isFinishing()) {
// Your Code
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm new to Android, and i've got some issues.
It looks like it's saying DB.EmployeeOperations.open() is having an null object passed to it, but I'm not sure.
Where I missed a step?
Any help is appreciated.
Thanks in advance.
Logcat:
* 06-10 16:10:52.605 17203-17203/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.androidtutorialpoint.employeemanagementsystem, PID: 17203
java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3019)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
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:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()' on a null object reference
at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3008)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
Java Code:
public class MainActivity extends AppCompatActivity{
private Button addEmployeeButton;
private Button editEmployeeButton;
private Button deleteEmployeeButton;
private Button viewAllEmployeeButton;
private EmployeeOperations employeeOps;
private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addEmployeeButton = (Button) findViewById(R.id.button_add_employee);
editEmployeeButton = (Button) findViewById(R.id.button_edit_employee);
deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee);
viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees);
addEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Add");
startActivity(i);
}
});
editEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndUpdateEmp();
}
});
deleteEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getEmpIdAndRemoveEmp();
}
});
viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ViewAllEmployees.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.employee_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_item_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getEmpIdAndUpdateEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
i.putExtra(EXTRA_ADD_UPDATE, "Update");
i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString()));
startActivity(i);
}
}).create()
.show();
}
public void getEmpIdAndRemoveEmp(){
LayoutInflater li = LayoutInflater.from(this);
View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set dialog_get_emp_id.xml to alertdialog builder
alertDialogBuilder.setView(getEmpIdView);
final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// get user input and set it to result
// edit text
employeeOps = new EmployeeOperations(MainActivity.this);
employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString())));
Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT);
t.show();
}
}).create()
.show();
}
#Override
protected void onResume() {
super.onResume();
employeeOps.open();
}
#Override
protected void onPause() {
super.onPause();
employeeOps.close();
}
}
The problem is you're calling employeeOps.open() in onResume(), but employeeOps is not instantiated yet, it's value is still null.
Take a look at the Activity lifecycle.
As you can see, when an Activity gets created two methods get called before onResume(): onCreate() and onStart().
If you would like to call the open() method of EmployeeOperations in onResume(), you need to have an instance of it by then.
Call the following in onCreate():
employeeOps = new EmployeeOperations(this);
Your problem is a misunderstanding of the Android lifecycle. Specifically, from that resource,
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
What this means for you is that onResume() triggers before you ever set employeeOps to a non-null value. You're only initializing it in response to a button press, but your Activity is only visible for a very short duration before onResume is triggered.