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.
Related
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 am working on project, which simply validates through username and password.
I made some progress with using DialogFragments and AlertDialog. AlertDialog appears after starting the app over the mainactivity asking for username and password.
I must set the Alertdialog's setCanceledOnTouchOutside(false) and DialogFragment's setCancelable(false) because I don't want the users to dismiss it with pressing android's back button.
The problem is, after dismissing it programatically on successful login, if the activity becomes invisible and visible again , the Alertdialog's OnShowListener called, showing this AlertDialog again.
Can I somehow "detach" this AlertDialog from Activity? This popups also happen after unlocking the screen and getting back to activity which makes it very annoying...
Here is the code of interest:
MainActivity
public class MainActivity extends AppCompatActivity implements NoticeDialogFragment.NoticeDialogListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(GlobalInformations.getInstance().getUsername()==null){
shownoticeDialog();
}
}
public void shownoticeDialog(){
DialogFragment dialogFragment = new NoticeDialogFragment();
dialogFragment.show(getFragmentManager(), "NoticeDialogFragment");
}
#Override
public void onDismiss(DialogFragment dialog) {
//set the username on a TextView instance, etc...
}
NoticeDialogFragment extends DialogFragment
public class NoticeDialogFragment extends DialogFragment {
public interface NoticeDialogListener{
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
public void onDismiss(DialogFragment dialog);
}
NoticeDialogListener mListener;
static Activity activity = null;
//static String username;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activity = (Activity) context;
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e){
throw new ClassCastException(activity.toString() + "must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_signin, null);
final AutoCompleteTextView actv_username = (AutoCompleteTextView) view.findViewById(R.id.username);
final EditText password = (EditText) view.findViewById(R.id.password);
getavailableusernames(actv_username);
final AlertDialog dialog = new AlertDialog.Builder(new ContextThemeWrapper(getContext(), R.style.AlertDialogCustom))
.setView(view)
.setTitle("Login")
.setPositiveButton("OK", null)
//.setNegativeButton("Cancel", null)
.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
final Button button =((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String passw = password.getText().toString();
String user = actv_username.getText().toString();
try{
if(user.length()<4 || passw.length()<4){
Toast.makeText(getContext(), "Username/password too short", Toast.LENGTH_SHORT).show();
dialog.show();
}
else {
//login to account, if success dismiss.
login(user, passw,dialog);
}
} catch(Exception e){
}
// dialog.dismiss();
}
});
}
});
dialog.setCanceledOnTouchOutside(false);
// set the DialogFragment to make the dialog unable to dismiss with back button
// (because not working if called on the dialog directly)
this.setCancelable(false);
return dialog;
}
public void login(final String username, String password, final AlertDialog dialog){
boolean login_success = false;
//query the credentials
login_success = dosomesqlquery(username, password);
if(login_success){
dialog.dismiss();
}
}
//passing the handling to activity...
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss(NoticeDialogFragment.this);
}
}
Thank you for your help and patience.
Well this is that kind of situation where I end up heading my desk continously.
The source of the problem was I called dialog.dismiss() which dismisses the dialog, BUT not the dialogfragment itself, so will never, ever dismissed, even if the dialog disappeared from screen. Placing this.dismiss() in NoticeDialogFragment's onDismiss or anywhere else after login succeded will let the application act as it should.
#Override
public void onDismiss(DialogInterface dialog) {
mListener.onDismiss(NoticeDialogFragment.this);
this.dismiss(); //will dismiss the DialogFragment. Yeeey!
}
Thank you for your time and answers as they helped me point out the real problem. I will modify the code based on your suggestions.
An easier way is to use a static variable in your activity using two steps.
Declare a global static boolean
private static boolean session = false;
Check if the boolean has changed and if not, set the boolean to true when the dialog is shown
public void shownoticeDialog(){
if(session)return;
DialogFragment dialogFragment = new NoticeDialogFragment();
dialogFragment.show(getFragmentManager(), "NoticeDialogFragment");
session = true;
}
Set the value when the activity goes background
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("authUser", GlobalInformations.getInstance().getUsername()==null)
}
and read it when it comes back
#Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState != null && savedInstanceState.containsKey("authUser")) {
boolean authUser = savedInstanceState.getBoolean("authUser", false);
if(authUser) {
//show or don't show dialog
}
}
}
This is my interface:
public interface TaskEditDialogListener {
public void passTask(String taskTitle, String note);
}
This is my Dialog Class
public class TaskEditDialog extends DialogFragment {
private TaskEditDialogListener mListerner;
public void setListerner(TaskEditDialogListener listerner) {
mListerner = listerner;
}
#BindView(R.id.dialog_TaskEdt)
EditText mTaskEdt;
#BindView(R.id.dialog_NotesEdt)
EditText mNoteEdt;
LayoutInflater inflater;
View v;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.task_edit_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ButterKnife.bind(getActivity());
String taskTitle = mTaskEdt.getText().toString();
String note = mNoteEdt.getText().toString();
mListerner.passTask(taskTitle,note);
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
return builder.create();
}
}
This is my Activity class
public class DetailedTaskActivity extends AppCompatActivity implements TaskEditDialogListener {
private String mTaskTitle;
// Bind the widget
#BindView(R.id.detailedTaskAct_TaskLabelTv)
TextView mTaskLabelTv;
#BindView(R.id.detailedTaskAct_TaskTv)
TextView mTaskTv;
#BindView(R.id.detailedTaskAct_DueDateLabelTv)
TextView mDueDateLabelTv;
#BindView(R.id.detailedTaskAct_DueDateTv)
TextView mDueDateTv;
#BindView(R.id.detailedTaskAct_NotesLabelTv)
TextView mNotesLabelTv;
#BindView(R.id.detailedTaskAct_NotesTv)
TextView mNotesTv;
#BindView(R.id.detailedTaskAct_PriorityLabelTv)
TextView mPriorityLabelTv;
#BindView(R.id.detailedTaskAct_PriorityTv)
TextView mPriorityTv;
#BindView(R.id.DetailedTaskAct_StatusLabelTv)
TextView mStatusLabelTv;
#BindView(R.id.detailedTaskAct_StatusTv)
TextView mStatusTv;
// Add delete button to Actionbar
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.delete_button, menu);
return true;
}
#Override
public void passTask(String taskTitle, String note) {
TaskEditDialog dialog = new TaskEditDialog();
dialog.setListerner(this);
Task task = new Select().from(Task.class).where("task_title = ?", mTaskTitle)
.executeSingle();
task.setTaskTitle(taskTitle);
task.setNotes(note);
mTaskTv.setText(taskTitle);
mNotesTv.setText(note);
}
}
I try to get the information from the dialog to the Activity and update a database and set the textview. However, I always receive the nullException Error like this
10-04 19:13:39.274 21018-21018/com.example.rubit1359.tudu E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rubit1359.tudu, PID: 20819
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.rubit1359.tudu.ui.dialog.TaskEditDialog$2.onClick(TaskEditDialog.java:49)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
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)
Please help me.
The error has nothing to do with sending data from DialogFragment to Activity. It's is due to NPE.
You are not correctly binding the views with ButterKnife in TaskEditDialog. It should be like this:
v = inflater.inflate(R.layout.task_edit_dialog, null);
ButterKnife.bind(this, v); // this refers to TaskEditDialog class object.
EDIT 1:
Since you are using DialogFragment, then you can directly communicate to its parent activity.
Do something like this:
((DetailedTaskActivity)getActivity()).passTask(someData); // where passTask() is any public method in the activity.
I am making an app that enables users to sign up on Parse.com. I have made Dialogs for the signing up just to add a more fluent feel in the app. So after they click "sign up" for example. I want it to take them to HomescreenActivity....So i made an intent inside of my Dialog. I know that It is a class and does not have context... but how would i make an intent inside of it? getContext() is not avaliable and getActivity() is giving me an error. I will post the code below. Thank you.
public class SignUpDialog extends DialogFragment {
private View v;
private LayoutInflater inflater;
private EditText adressEditText, fullnameEditText , passwordEditText , usernameEditText;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
inflater = getActivity().getLayoutInflater();
v = inflater.inflate(R.layout.sign_up_dialog_layout , null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v).setPositiveButton("Sign Up!" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
fullnameEditText = (EditText) v.findViewById(R.id.fullNameEditTextLayout);
passwordEditText = (EditText) v.findViewById(R.id.passwordEditTextLayout);
usernameEditText = (EditText) v.findViewById(R.id.usernameEditTextLayout);
adressEditText = (EditText) v.findViewById(R.id.addressEditTextLayout);
String username = usernameEditText.getText().toString().trim();
String password = usernameEditText.getText().toString();
String address = adressEditText.getText().toString();
Toast.makeText(getActivity() , "We are signing you u now!" , Toast.LENGTH_SHORT).show();
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password);
user.put("address", address);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
Intent intent = new Intent(getActivity(), HomescreenActivity.class);
getActivity().startActivity(intent);
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
}
}
});
}
}).setNegativeButton("Cancel" , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
Here is the error i am getting
java.lang.NullPointerException
at com.xxx.xxx.dialogs.SignUpDialog$2$1.done(SignUpDialog.java:69)
at com.xxx.xxx.dialogs.SignUpDialog$2$1.done(SignUpDialog.java:63)
at com.parse.Parse$5.done(Parse.java:903)
at com.parse.Parse$5.done(Parse.java:900)
at com.parse.Parse$6$1.run(Parse.java:944)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
In Fragments you need to null check getActivity() since the Fragment can outlive the Activity.
Alternatives to getActivity() and getContext() are:
getApplicationContext()
Or, to create a context that is available anywhere in your app, you can extend Application and create your custom application class.
Inside your custom application class you create a static variable:
private static final CustomApplication INSTANCE;
In CustomApplication's onCreate():
INSTANCE = this;
Create a static method
public static CustomApplication getInstance() {
return INSTANCE;
}
Then from anywhere in your app, to get the context, you can call:
CustomApplication.getInstance()
which is a context.
i am new to developing apps for android and i want to create a simple Conterter app, just for the start. In my view i have a edittext and a Button. If i click the button, it will open a AlertDialog with list of strings. I cant figure out how to manage this: When i click on one item in the AlertView i want to set the text of the button to the selected string and dismiss the AlertDialog. Can somebody please help me ?
public class VypocetDlzkyActivity extends Activity {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vypocet_dlzky);
}
public void zmenPrevodZ(View view){
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(VypocetDlzkyActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,null);
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
dialog.cancel();
}
};
final AlertDialog alert = builder.create();
alert.show();
}
You need to set the values of these 2 member variables in your onCreate() method, like this:
HodnotaDlzka = (EditText)findViewById(R.id.xxxx);
prevodDlzkaZtlacidlo = (Button)findViewById(R.id.yyyy);
xxxx is the ID you gave the EditText in activity_vypocet_dlzky.xml and yyyy is the ID you gave to the Button.
Also, after a button is clicked in the AlertDialog, the dialog is automatically dismissed, so you don't need to call dialog.cancel().
Problem is you didnt add any onClick listnerz.On clicking on button you need to call the required method.
public class MainActivity extends Activity implements OnClickListener {
EditText HodnotaDlzka;
Button prevodDlzkaZtlacidlo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HodnotaDlzka = (EditText) findViewById(R.id.e1);
prevodDlzkaZtlacidlo = (Button) findViewById(R.id.b1);
prevodDlzkaZtlacidlo.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String[] jednotkyDlzky = {"milimeter", "centimeter", "decimeter", "meter", "kilometer", "svetelny rok"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Vyberte jednotku");
builder.setItems(jednotkyDlzky,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
String value = jednotkyDlzky[item].toString();
prevodDlzkaZtlacidlo.setText(value);
}
});
enter code here
final AlertDialog alert = builder.create();
alert.show();
}
}