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.
Related
I'm new to android and trying to pass rating bar to dialog but it throws a NPE.
This the code on my oncreate activity.
…
LinearLayout rating = findViewById(R.id.rating);
ratingBar = findViewById(R.id.ratingsbar);
flag = true;
rating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (flag) {
RatingBarDialog ratingBarDialog = new RatingBarDialog();
Bundle args = new Bundle();
args.putString("profileUid", profileUid);
ratingBarDialog.setArguments(args);
ratingBarDialog.show(getFragmentManager(), "rating");
}
}
});
I have method for adding rating in the same class
static public void addRatingToUser(float newRating, String profileUid) {
// calculate new rating within User class
dbUser.addRating((double) newRating);
// add new rating and ratingCount to firebase
DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users").child(profileUid);
userRef.child("rating").setValue(dbUser.getRating());
userRef.child("ratingCount").setValue(dbUser.getRatingCount());
// set the stars of the ratingBar view
ratingBar.setRating((float) dbUser.getRating());
}
}
Here is my RatinDialog class
public class RatingBarDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = LayoutInflater.from(builder.getContext());
#SuppressLint("InflateParams") final View view = inflater.inflate(R.layout.activity_rate_user, null);
final RatingBar ratingBar = view.findViewById(R.id.editRatingBar);
final String profileUid = getArguments().getString("profileUid");
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
.setTitle("Rate User")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
UserProfile.addRatingToUser(ratingBar.getRating(), profileUid);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
RatingBarDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
I have a model user with method for calculating ratings
void addRating(double newRating) {
// get total of all old ratings (multiply current average rating by # of ratings
double oldRatingTotal = rating * ratingCount;
// increment rating count
ratingCount++;
// add new rating to the total, then divide it by the new rating count to get new average
double newRatingTotal = oldRatingTotal + newRating;
rating = newRatingTotal / ratingCount;
}
This is my logcat error, I've tried but unable to fix the NPE. I'll appreciate any help.
Thank you
2018-12-18 19:49:56.710 27009-27009/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.reseller, PID: 27009
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.android.reseller.User.addRating(double)' on a null object reference
at com.android.reseller.UserProfile.addRatingToUser(UserProfile.java:215)
at com.android.reseller.RatingBarDialog$2.onClick(RatingBarDialog.java:38)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6566)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$Metho
Finally, I was able to fix the error.
I initially, created a variable of the model:
static User dbUser;
But failed to create an object of the model in my oncreate method, this lead to dbUser being null.
dbUser = new User();
My progress bar is just a spinner.
I am showing two options to user and when user clicks an option, I show a dialog, so that user reads and understands it.
This is what I want.
When they click positive, it should show the spinner and keep calling service on background.
When they click negative, it should make the option unchecked.
Here is the code.
This radioGroup.setOnClickListener goes into onCreateView method of a fragment.
public class Choose_CountryFragment extends Fragment {
private RadioGroup radioGroup;
private TextView textView;
private String countryChosen = null;
ConnectionStatus connectionStatus = new ConnectionStatus(getContext());
public Choose_CountryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_choose__country, container, false);
radioGroup = (RadioGroup) rootView.findViewById(R.id.country_choice_radio);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.countryCanada:
// do operations specific to this selection
countryChosen = "Canada";
Intent explicitServiceIntent = new Intent(getActivity(), Service.class);
explicitServiceIntent.putExtra("country", "Canada");
getActivity().startService(explicitServiceIntent);
connectionStatus.showProgress();
break;
case R.id.countryUSA:
countryChosen = "USA";
Dialog dialog = onCreateDialog(savedInstanceState);
dialog.show();
connectionStatus.showProgress();
break;
}
}
});
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Toast.makeText(getContext(), "Click Got it", Toast.LENGTH_LONG).show();
builder.setMessage(R.string.SignUpWarningInfo)
.setPositiveButton(R.string.gotIt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent explicitServiceIntentUSA = new Intent(getActivity(), Service.class);
explicitServiceIntentUSA.putExtra("country", countryChosen );
getActivity().startService(explicitServiceIntentUSA);
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
}
ConnectionStatus.java
public class ConnectionStatus {
private Context _context;
private ProgressDialog progressDialog = null;
public ConnectionStatus(Context context) {
this._context = context;
}
public void showProgress(){
progressDialog = new ProgressDialog(_context);
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
}
Error happens when I click USA.
Error I get
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154)
at android.app.AlertDialog.<init>(AlertDialog.java:109)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at com.a2.a2.ConnectionStatus.showProgress(ConnectionStatus.java:66)
at com.a2.a2.signUp.Choose_CountryFragment$1.onCheckedChanged(Choose_CountryFragment.java:73)
Your Context returning null
Change code in Choose_CountryFragment
public class Choose_CountryFragment extends Fragment {
...
protected Context mContext;
private ConnectionStatus connectionStatus
...
public Choose_CountryFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_choose__country, container, false);
...
connectionStatus = new ConnectionStatus(mContext);// initialize ConnectionStatus here
...
}
}
Override onAttach Inside Choose_CountryFragment
#Override
public void onAttach(Context context) {
super.onAttach(context);
mContext = context;
}
In Fragment, you have to use:
ProgressDialog progressDialog = new ProgressDialog(getActivity);
From the documentation, the getActivity() method returns the Activity this Fragment is currently associated with it.
Edit:
In Activity class, you have to use like:
ProgressDialog progressDialog = new ProgressDialog(YourActivityClassName.this);
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.
Could you please help with the below:
I am trying to call the method deletePlayer inside the fragment PlayersActivityFragment from the alertdialog NameAlertDialogFragment.
The code is below:
public static class PlayersActivityFragment extends Fragment {
ArrayList<Player> arrayPlayers;
ListView listViewPlayers;
//PlayerAdapter adapter;
public PlayersActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arrayPlayers = new ArrayList<Player>();
View rootView = inflater.inflate(R.layout.fragment_activity_players, container, false);
Button buttonAddPlayer = (Button) rootView.findViewById(R.id.button_addplayers);
buttonAddPlayer.setOnClickListener(new View.OnClickListener(){
public void onClick(View view) {
arrayPlayers.add(new Player("Player", 0));
Player selectedPlayer = arrayPlayers.get(arrayPlayers.size()-1);
((PlayersActivity)getActivity()).showNameDialogFragment(selectedPlayer);
}
});
listViewPlayers = (ListView) rootView.findViewById(R.id.listView_playername);
return rootView;
}
public void deletePlayer(){
arrayPlayers.remove(arrayPlayers.size()-1);
}
}
void showNameDialogFragment(Player player) {
mDialog = NameAlertDialogFragment.newInstance(player);
mDialog.show(getFragmentManager(),"SCORE DIALOG");
}
// Class that creates the AlertDialog
public static class NameAlertDialogFragment extends DialogFragment {
static Player selectedPlayer;
public static NameAlertDialogFragment newInstance(Player player) {
selectedPlayer = player;
return new NameAlertDialogFragment();
}
// Build AlertDialog using AlertDialog.Builder
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.alertdialog_name, null);
final EditText editTextName = (EditText) view.findViewById(R.id.edittext_name);
return new AlertDialog.Builder(getActivity())
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
.setView(view)
.setMessage("Enter Player's Name:")
//Set up Yes Button
.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, int id) {
mName = editTextName.getText().toString().trim();
selectedPlayer.setName(mName);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
//playersActivityFragment.deletePlayer();
//((PlayersActivityFragment)getTargetFragment()).deletePlayer();
NameAlertDialogFragment.this.getDialog().cancel();
}
})
.create();
}
}
The two different ways I have tried to call the methods are commented out in the .setNegativeButton onClickListener:
PlayersActivityFragment playersActivityFragment = (PlayersActivityFragment) getFragmentManager().findFragmentById(R.id.container);
playersActivityFragment.deletePlayer();
and
((PlayersActivityFragment)getTargetFragment()).deletePlayer();
Thank you!
First of all, why are all of your classes static? Anyway, here's an answer that should work...
Try using an interface as a callback. For example:
First create an interface.
public interface NameAlertDialogListener {
public void onNegativeClick();
}
Then have PlayersFragment implement NameAlertDialogListener.
public static class PlayersActivityFragment extends Fragment implements NameAlertDialogListener
Next, in the PlayersFragment, create a method called onNegativeClick.
#Override
public void onNegativeClick() {
//delete or whatever you want to do.
}
Create a member variable for the listener:
static Player selectedPlayer;
static NameAlertDialogListener mCallBack;
Next create a method in the dialog fragment called setListener.
public void setListener(NameAlertDialogListener callback) {
try {
mCallBack = callback;
} catch (ClassCastException e){
throw new ClassCastException(callback.toString() + " must implement NameAlertDialogListener" );
}
}
Then, when you create the dialog fragment call the setListener method.
void showNameDialogFragment(Player player) {
mDialog = NameAlertDialogFragment.newInstance(player);
mDialog.setListener(this);
mDialog.show(getFragmentManager(),"SCORE DIALOG");
}
Lastly, in your negative click listener:
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mCallBack.onNegativeClick() ;
NameAlertDialogFragment.this.getDialog().cancel();
}
})
I am not sure if this is the correct way of doing things, but I have come to a working solution.
First I moved ArrayList<Player> arrayPlayers; outside of the PlayersActivityFragment fragment.
Then I moved the method:
public void deletePlayer(){
arrayPlayers.remove(arrayPlayers.size()-1);
}
outside of the PlayersActivityFragment fragment.
I then called the deletePlayer() method inside the alertdialog with the line ((PlayersActivity)getActivity()).deletePlayer();.
Actually, I have a little hack, it's not really good, but it's easy to implement: declare PlayersActivityFragment variable in your DialogFragment. Then change your constructor to:
public static NameAlertDialogFragment newInstance(Player player,PlayersActivityFragment fragment ){
selectedPlayer = player;
NameAlertDialogFragment test = new NameAlertDialogFragment();
test.playerActivityFragment = fragment;
return test;
}
Then you can call playerActivityFragment.deletePlayer() everywhere in your DialogFragment.
P/s: The best way is implement interface, but for lazy coder like me, the method above is better lol!
I am trying to implement custom DialogFragment. But when I try to show it I am getting NullPointerException. Also as I have noticed onCreateDialog is never implictly called.
What is wrong with it. I have read official manual, and followed all steps in it DialogFragment
Here is my code for custom Dialog Fragment
public class UserInputDialogFragment extends DialogFragment {
InputDialogListener mListener;
private EditText mTextEdit;
public UserInputDialogFragment() {
super();
}
// Use this instance of the interface to deliver action events
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
View mainView = inflater.inflate(R.layout.dialog_input, null);
builder.setView(mainView);
mTextEdit = (EditText) mainView.findViewById(R.id.user_input);
if (mTextEdit==null) {
Log.e("ERROR","Text edit is null");
}
// Add action buttons
builder.setPositiveButton(R.string.ok_btn, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(UserInputDialogFragment.this,mTextEdit.getText().toString());
}
});
builder.setNegativeButton(R.string.cancel_bnt, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogNegativeClick(UserInputDialogFragment.this,mTextEdit.getText().toString());
UserInputDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
public interface InputDialogListener {
public void onDialogPositiveClick(DialogFragment dialog, String userInput);
public void onDialogNegativeClick(DialogFragment dialog, String userInput);
}
public void showAndAddHint(FragmentManager manager,String tag,String hint) {
this.onCreateDialog(null);
mTextEdit.setHint(hint);
this.show(manager,tag);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (InputDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement InputDialogListener");
}
}
}
And I am trying to show dialog this way.
UserInputDialogFragment userInputDialogFragment = new UserInputDialogFragment();
userInputDialogFragment.showAndAddHint(getFragmentManager(),"Please enter phone number",task.phoneNumber);
And here is NullPointerException mTextEdit is null.
public void showAndAddHint(FragmentManager manager,String tag,String hint) {
this.onCreateDialog(null);
mTextEdit.setHint(hint);
this.show(manager,tag);
}
The showAndAddHint method won't work as written. What you should do instead is:
1 - Set a member variable mHint = hint;
2 - Call show() exactly the way you're doing it now.
3 - Read the member variable mHint in on create dialog and use it to set the edit text hint.
Don't call onCreateDialog explicitly because the show method does that for you when needed.