Problem with Positive And Negative Button in singleshoicedialog - java

I have a bottom navigation fragment and i want to show a single choice dialog in a fragment when a button clicked but i have this logcat:
2020-06-24 18:47:27.954 18946-18946/app E/AndroidRuntime: FATAL EXCEPTION: main
Process: app, PID: 18946
java.lang.NullPointerException: Attempt to invoke interface method 'void app.MapChoiceFragment$SingleChoiceListener.OnNegativeButtonClickedMap()' on a null object reference
at app.baharestanschool.ir.MapChoiceFragment$1.onClick(MapChoiceFragment.java:55)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:174)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:941)
here is my error's code:
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final String[] item = getActivity().getResources().getStringArray(R.array.addresses);
builder.setTitle("choose")
.setSingleChoiceItems(item, position, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
position=i;
}
})
.setPositiveButton("O", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnPosetiveButtonClickedMap(item,position);
}
})
.setNegativeButton("c", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnNegativeButtonClickedMap();
}
});
return builder.create();
}

You should create a dialog as below:-
public class CustomDialogFragment extends DialogFragment {
private OnButtonClickListener mlistener;
public interface OnButtonClickListener {
void OnPositiveButtonClickedMap(String[] item, int position);
void OnNegativeButtonClickedMap();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mlistener = (OnButtonClickListener) getActvity();
} catch (Exception e) {
}
}
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final String[] item = getActivity().getResources().getStringArray(R.array.addresses);
builder.setTitle("choose")
.setSingleChoiceItems(item, position, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
position=i;
}
})
.setPositiveButton("O", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnPositiveButtonClickedMap(item,position);
}
})
.setNegativeButton("c", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mlistener.OnNegativeButtonClickedMap();
}
});
return builder.create();
}
}
In your Activity, implements OnButtonClickListener as below:-
class MyActivity extends Activity implements OnButtonClickListener {
}
For more info click here

You can build your own Dialog. I build my own custom Dialog With the following example enter link description here

Related

I want to add sub tasks on clicking the task but I get the following error when ever I click the task

The error that I get when clicking on a task inorder to add the subtasks:
2020-04-23 14:52:48.749 12289-12289/com.example.justdoit E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.justdoit,
PID: 12289 java.lang.RuntimeException: Unable to start activity ComponentInfo {
com.example.justdoit/com.example.justdoit.ItemActivity
}
: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.justdoit.ItemActivity.onCreate(ItemActivity.java:61) at android.app.Activity.performCreate(Activity.java:7009) at android.app.Activity.performCreate(Activity.java:7000) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6494) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
ItemActivity Class:
public class ItemActivity extends AppCompatActivity {
Toolbar item_toolbar;
RecyclerView rv_item;
FloatingActionButton fab_item;
long todoId=-1;
ItemActivity activity;
DBHandler dbHandler;
ItemTouchHelper touchHelper;
ItemAdapter adapter;
ArrayList<ToDoItem>list;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
item_toolbar=findViewById(R.id.item_toolbar);
rv_item=findViewById(R.id.rv_item);
fab_item=findViewById(R.id.fab_item);
setSupportActionBar(item_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(getIntent().getStringExtra(INTENT_TODO_NAME));
todoId=getIntent().getLongExtra(INTENT_TODO_ID, -1);
activity=this;
dbHandler=new DBHandler(activity);
rv_item.setLayoutManager(new LinearLayoutManager(activity));
fab_item.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Add ToDo item");
View view=getLayoutInflater().inflate(R.layout.dialog_dashboard, null);
final EditText toDoName=view.findViewById(R.id.ev_todo);
dialog.setView(view);
dialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialog, int i) {
if (toDoName.getText().toString().length() > 0) {
ToDoItem item=new ToDoItem();
item.setItemName(toDoName.getText().toString());
item.setToDoId(todoId);
item.setCompleted(false);
dbHandler.addToDoItem(item);
refreshList();
}
}
}
);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {}
}
);
dialog.show();
}
}
);
touchHelper=new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 0) {
#Override public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder p1, #NonNull RecyclerView.ViewHolder p2) {
int sourcePosition=p1.getAdapterPosition();
int targetPosition=p2.getAdapterPosition();
Collections.swap(list, sourcePosition, targetPosition);
adapter.notifyItemMoved(sourcePosition, targetPosition);
return true;
}
#Override public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int i) {}
}
);
touchHelper.attachToRecyclerView(rv_item);
}
#Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==android.R.id.home) {
finish();
return true;
}
else return super.onOptionsItemSelected(item);
}
#Override protected void onResume() {
refreshList();
super.onResume();
}
void refreshList() {
list=dbHandler.getToDoItems(todoId);
adapter=new ItemAdapter(activity);
rv_item.setAdapter(adapter);
}
void updateItem(final ToDoItem item) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Update ToDo Item");
View view=getLayoutInflater().inflate(R.layout.dialog_dashboard, null);
final EditText toDoName=view.findViewById(R.id.ev_todo);
toDoName.setText(item.getItemName());
dialog.setView(view);
dialog.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {
if (toDoName.getText().toString().length() > 0) {
item.setItemName(toDoName.getText().toString());
item.setToDoId(todoId);
item.setCompleted(false);
dbHandler.updateToDoItem(item);
refreshList();
}
}
}
);
dialog.show();
}
class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> {
ItemActivity activity;
ItemAdapter(ItemActivity activity) {
this.activity=activity;
}
#NonNull #Override public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
return new ViewHolder(LayoutInflater.from(activity).inflate(R.layout.rv_child_item, viewGroup, false));
}
#Override public void onBindViewHolder(#NonNull final ViewHolder holder, final int i) {
holder.itemName.setText(list.get(i).getItemName());
holder.itemName.setChecked(list.get(i).isCompleted());
holder.itemName.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
list.get(i).setCompleted(!list.get(i).isCompleted());
activity.dbHandler.updateToDoItem(list.get(i));
}
}
);
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
AlertDialog.Builder dialog=new AlertDialog.Builder(activity);
dialog.setTitle("Are you sure");
dialog.setMessage("Do you want to delete this item?");
dialog.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int pos) {
activity.dbHandler.deleteToDoItem(list.get(i).getId());
activity.refreshList();
}
}
);
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override public void onClick(DialogInterface dialogInterface, int i) {}
}
);
dialog.show();
}
}
);
holder.edit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
activity.updateItem(list.get(i));
}
}
);
holder.move.setOnTouchListener(new View.OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN) {
activity.touchHelper.startDrag(holder);
}
return false;
}
}
);
}
#Override public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
CheckBox itemName;
ImageView edit;
ImageView delete;
ImageView move;
ViewHolder(View v) {
super(v);
itemName=v.findViewById(R.id.cb_item);
edit=v.findViewById(R.id.iv_edit);
delete=v.findViewById(R.id.iv_delete);
move=v.findViewById(R.id.iv_move);
}
}
}
}
When I click on the task to add sub tasks, the app stops working and shuts down immediately showing the following error that I've attached.
I want to add sub tasks by clicking on the main task, but I'm not able to do it. How can I do that?
I've declared the FloatingActionButton as fab_item and have written:
fab_item = findViewById(R.id.fab_item);
before the onClick under the onCreate.
Declare this as your Class property:
FloatingActionButton fab_item = findViewById(R.id.fab_item);
Instead of initializing your fab_item in the onCreate(), try to initialize it in the class definition.

How can I pass an ArrayList of Strings between a Class and an Activity?

I have a problem with passing an ArrayList<String>between Class and Activity.
I know I can use Intent for passing an array between Activities but I don't know how to do this with Class and Activities. Please help
this is my class
public class MultipleChoiceDialogFragment extends DialogFragment implements Serializable {
public interface onMultiChoiceListener{
void onPositiveButtonClicked(String[] list , ArrayList<String> selectedItemList);
void onNegativeButtonClicked()
;
}
onMultiChoiceListener mlistner;
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
mlistner = (onMultiChoiceListener) context;
} catch (Exception e) {
e.printStackTrace();
throw new ClassCastException(getActivity().toString()+"onMultiChoiceListener must implemented");
}
}
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final ArrayList<String> selectedItemList = new ArrayList<>();
// Intent i = new Intent(getContext(),MultipleChoiceDialogFragment.class);
// i.putStringArrayListExtra("arrayfinal",selectedItemList);
AlertDialog.Builder mbuilder = new AlertDialog.Builder(getActivity());
final String[] list = getActivity().getResources().getStringArray(R.array.selectableRole);
mbuilder.setTitle("Chose Role").setMultiChoiceItems(list, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int i, boolean b) {
if (b){
selectedItemList.add(list[i]);
}else {
selectedItemList.remove(list[i]);
}
}
})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
mlistner.onPositiveButtonClicked(list, selectedItemList);
}
})
.setNegativeButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mlistner.onNegativeButtonClicked();
}
});
return mbuilder.create();
}
}
i want use final list in another activity

How to show a customized DialogFragment in the activity [duplicate]

This question already has answers here:
Problem inflating custom view for AlertDialog in DialogFragment
(9 answers)
Closed 7 years ago.
I am trying to build an AlertDialog and want to show it when the main activity starts. But when the activity starts, an error comes up:
android.util.AndroidRuntimeException: Window feature must be requested before adding content
What I do first is creating an AlertFragment:
public class AlertFragment extends DialogFragment{
public static AlertFragment newInstance(){
return new AlertFragment();
}
public AlertFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle SavedInstanceState){
super.onCreateView(inflater, container, SavedInstanceState);
return inflater.inflate(R.layout.alert_dialog, container, false);
}
#Override
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).create();
}
}
The following is the main activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertFragment AF = AlertFragment.newInstance();
AF.show(getSupportFragmentManager(), "Dialog");
}
}
Can someone tell me where the problem lies?
In your AlertFragment remove oncreateview and run
public class AlertFragment extends DialogFragment{
public static AlertFragment newInstance(){
return new AlertFragment(); }
public AlertFragment(){}
#Override
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).create();
}
}
just use show in place of create in your code like following:
public Dialog onCreateDialog(Bundle SaveInstanceState){
return new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), android.R.style.Theme_Dialog)).setMessage("Alert Dialog").setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Positive", Toast.LENGTH_SHORT).show();
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Negative", Toast.LENGTH_SHORT).show();
}
}).show();

Passing Events Back to the Dialog's Host when host is a RecyclerView.ViewHolder

I have a list of cards with a button on each one. When clicked it opens a dialog and allows the user to select an integer value. When the dialogue is closed I want the value to be passed back to the card so some text can be updated.
This is the extension of the RecyclerView.ViewHolder OnClick event for the button:
public class CardEvent extends RecyclerView.ViewHolder implements SetReminderDialogFragment.SetReminderDialogListener {
...
#Override
public void onClick(View v) {
FragmentManager f = ((FragmentActivity) v.getContext()).getSupportFragmentManager();
SetReminderDialogFragment d = new SetReminderDialogFragment();
...
d.show(f, "reminder");
}
These are the callbacks that update the card, also in RecyclerView.ViewHolder extension (nothing in them yet):
#Override
public void onDialogPositiveClick(DialogFragment dialog) { }
#Override
public void onDialogNeutralClick(DialogFragment dialog) { }
...
}
Then there is the dialog fragment:
public class SetReminderDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
...
builder.setView(view)
...
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Do Nothing - Just Dismiss
}
});
if (i != null)
{
builder.setNeutralButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
...
Listener.onDialogNeutralClick(SetReminderDialogFragment.this);
}
})
.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
...
Listener.onDialogPositiveClick(SetReminderDialogFragment.this);
}
});
} else {
builder.setPositiveButton("Set", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
...
Listener.onDialogPositiveClick(SetReminderDialogFragment.this);
}
});
}
return builder.create();
}
This is supposed to implement the callback functionality, as per this link:
public interface SetReminderDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNeutralClick(DialogFragment dialog);
}
SetReminderDialogListener Listener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
Listener = (SetReminderDialogListener) activity;
} catch (ClassCastException f) {
throw new ClassCastException(activity.toString()
+ " must implement SetReminderDialogListener");
}
}
However, the activity of course does not implement the callback interface. I can't use setTargetFragment either, since it is not an extension of Fragment. How can I pass back this value to the card that called the dialog, or at least inform it that the dialog has been dismissed (preferably with a parameter of which button has been pressed), so it can update its contents?
Many Thanks

How to pass values from DIalog class to it's host

So this is my Dialog class:
public class SecondActivity extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.second, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}
}
In my dialog there are 2 edit texts which get 2 strings. I want to use those 2 strings in my MainActivity if the user presses on the save button. How do I do that?
The inflate method returns a view where you can execute a findViewById, like the following:
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.second, null);
EditView editView = (EditView)v.findById(R.id.your_edit_view);
builder.setView(v)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}

Categories