Sending the data back to the activity from alertDialog - java

Hello guys need some help i created a custom alertdialog which takes user input like username and password. i followed the android developers site What i want to do is once the user enters the username and password and press the sign in button in alertdialog i want to show these values to the activity which created the dialog. i am stuck on this wasted 3 hours on this. Any help would be much appreciated. This is my code.
MainActivity.java
public class MainActivity extends FragmentActivity implements NoticeDialogFragment.NoticeDialogListener{
private Button dialogButton;
private Button customDialogButton;
private TextView customDialogTextview;
private Button dialogWithInterface;
private EditText dialogUsername;
private EditText dialogPassword;
String username;
String password;
public void showNoticeDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new NoticeDialogFragment();
dialog.show(getFragmentManager(), "NoticeDialogFragment");
}
// The dialog fragment receives a reference to this Activity through the
// Fragment.onAttach() callback, which it uses to call the following methods
// defined by the NoticeDialogFragment.NoticeDialogListener interface
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
// User touched the dialog's positive button
}
#Override
public void onDialogNegativeClick(DialogFragment dialog) {
// User touched the dialog's negative button
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customDialogTextview = (TextView)findViewById(R.id.customdialogtext);
customDialogTextview.setText("Email and Password: ");
dialogButton = (Button)findViewById(R.id.dialogbutton);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// 1. Instantiate an AlertDialog.Builder with its constructor
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Add the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// User clicked OK button
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// User cancelled the dialog
}
});
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage("hello")
.setTitle("Dialog");
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
});
customDialogButton = (Button)findViewById(R.id.customdialogbutton);
customDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Get the layout inflater
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog, null));
builder.setPositiveButton("Sign In", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sign in the user
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
dialogWithInterface = (Button)findViewById(R.id.dialogwithinterface);
dialogWithInterface.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showNoticeDialog();
}
});
}
NoticeDialogFragment.java
public class NoticeDialogFragment extends DialogFragment {
/* The activity that creates an instance of this dialog fragment must
* implement this interface in order to receive event callbacks.
* Each method passes the DialogFragment in case the host needs to query it. */
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
// Use this instance of the interface to deliver action events
NoticeDialogListener mListener;
// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener
#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 = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog, null));
builder.setPositiveButton("Sign In", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
mListener.onDialogPositiveClick(NoticeDialogFragment.this);
Toast.makeText(getActivity(), "positive", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the negative button event back to the host activity
mListener.onDialogNegativeClick(NoticeDialogFragment.this);
}
});
return builder.create();
}
}

Look at this method your activity implements:
#Override
public void onDialogPositiveClick(DialogFragment dialog) {
// User touched the dialog's positive button
}
It is apart of the custom interface you created in the dialog called NoticeDialogListener and is the way you want the dialog to communicate with the activity that called it.
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
Change this so that onDialogPostiveClick looks something like:
public void onDialogPositiveClick(String name, String password);
and pass the values from your EditText into the call when the button is clicked like so:
builder.setPositiveButton("Sign In", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
mListener.onDialogPositiveClick(mNameEdit.getText().toString(), mPasswordEdit.getText().toString());
}
});
The next step would be to do whatever you wanted to do with the name and password values in your method you override in your activity for the onDialogPositiveClick() method.
#Override
public void onDialogPositiveClick(String name, String password) {
//do something with name and password here?
}
This seems like the easiest way to do what it is you want to do with your already existing code.

Related

call method from another class when button in pop up window is pressed

I have this code in Dialog class:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("MyTitle")
.setMessage("MyMessage")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/////////LINE OF MY QUESTION/////////////////////
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
and I need to call method "OK_Clicked" from another class (MainActivity) inside OnClickListener for "OK" button (///LINE OF MY QUESTION///). I have tried it with:
MainActivity xyz = new MainActivity();
xyz.OK_Clicked();
But every time when I click "OK" button, the app just crashes saying: "MyApp has stopped."
Define the DialogInterface.OnClickListener outside of where you need it (as in, assign it to a class level variable) and then create a method for calling its onClick method from outside the class.
//Just take your existing anonymous subclass definitions and put them here
private DialogInterface.OnClickListener listener1 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
};
private DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("MyTitle")
.setMessage("MyMessage")
.setPositiveButton("OK", listener1)
.setNegativeButton("Cancel", listener2);
return builder.create();
}
// Call these methods from outside this class
public void onClick1(){
listener1.onClick();
}
public void onClick2(){
listener2.onClick();
}

Open two dialog together

I have two dialog.i open dialog one and click one button in adapter listview in dialog, and i want open another dialog to ask question for are you sure delet this item or no.
But just i can open one of them at a time.
What can i do?
viewHolder.btnDelet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DialogDelet(context).setOnListener(new ListenerDelet() {
#Override
public void onSuccess() {
listenerAdapterUserAndRole.unSelect(item);
}
#Override
public void onCancel() {
}
}).Show();
}
});
You can cancel first dialog when user is confirm or you want to open next dialog
like:
public void open(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure,
You wanted to make decision");
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(MainActivity.this,"You clicked yes
button",Toast.LENGTH_LONG).show();
//cancel first dialog here
firstDialogObj.cancel;
// do your stuff contnious what you want
}
});
alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}

Get Dialog's on click listener into my Activity from separate Dialog class

I have a Dialog class where I have kept my dialogs. Now the problem is that I want to get the View click listeners of my dialog back in my activity. I know this can be done by writing an interface but is there any other OOP way of doing it?
My Dialog class:
public class Dialogs{
public void testCompletionDialog() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.test_complete_dialog);
dialog.setTitle("Ratta provet?");
dialog.findViewById(R.id.lesson_btn_marker).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I want my activity to know that this view is clicked.
dialog.dismiss();
}
});
dialog.findViewById(R.id.lesson_btn_ratta).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I want my activity to know that this view is clicked.
}
});
dialog.show();
}
}
My Activity:
if (areQueOver) {
Dialogs dialogs=new Dialogs(TestActivity.this);
dialogs.testCompletionDialog();
}
You may use it using EventBus
Inside your onClick in your Dialog class post an event telling that a dialog has been clicked. The event may contain a string variable telling which dialog is clicked.
Inside your Activity subscribe to and handle the event. You may check the String variable value to know which dialog was clicked.
Modify your Dialogs class as below:
public class Dialogs{
public void testCompletionDialog() {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.test_complete_dialog);
dialog.setTitle("Ratta provet?");
dialog.findViewById(R.id.lesson_btn_marker).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post("btn_marker");
dialog.dismiss();
}
});
dialog.findViewById(R.id.lesson_btn_ratta).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventBus.getDefault().post("btn_ratta");
}
});
dialog.show();
Inside your Activity:
#Subscribe(threadMode = ThreadMode.MAIN) public void onEvent(String action){
if(action.equals("btn_ratta")){
} else if(action.equals("btn_marker")) {
}
}
inside onCreate add this-
EventBus.getDefault().register(this);
inside onDestroy add this-
EventBus.getDefault().unregister(this);
Alternative method:
Well, other than interface and EventBus, you may add a public method to your Activity say,
onDialogClicked(String dialogName){//TODO handle the click as per dialogName}
and then call this method from your onClick in your Dialogs class.
Create an interface.
public interface OnDialogConfirmClickListener {
void onDialogConfirmClick(Class parameter//or empty);
}
Implement this interface to your activity.
public class MainActivity extends Activity implements OnDialogConfirmClickListener {
...
}
Send interface as parameter to Dialogs or testCompletionDialog method.
public void testCompletionDialog(OnDialogConfirmClickListener listener) {
...
dialog.findViewById(R.id.lesson_btn_marker).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onDialogConfirmClick(parameter//or empty);
dialog.dismiss();
}
});
...
}
use listner for call buttons like this
Simpledialoginterface listner = new Simpledialoginterface() {
#Override
public void ok_button() {
//ok button click
}
#Override
public void cancel_button() {
//cancel button click
}
};
use this dialog
public static void popupnew(String tittle, String message, String Button, String Cancel,
final Activity context, final Simpledialoginterface listner) {
if (!((Activity) context).isFinishing()) {
android.app.AlertDialog.Builder alertDialog;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alertDialog = new android.app.AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
alertDialog = new android.app.AlertDialog.Builder(context);
}
alertDialog.setTitle(tittle);
alertDialog.setMessage(message);
alertDialog.setPositiveButton(Button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
listner.ok_button();
}
});
alertDialog.setNegativeButton(Cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
listner.cancel_button();
}
});
alertDialog.show();
}
}
//interface class
public interface Simpledialoginterface {
public void ok_button();
public void cancel_button();
}
popupnew("title","message","OK","Cancel",this,listner);//call dialog
Yes if you want to call any method of Actvity then you can call through context of Activity :
suppose method1() is under Activity and you want to call from Dailog then you can call through .
((MyActivity)((Activity)context)).method1();

How to open a DialogFragment by clicking on a TextView

I have a MainActivity like this one below:
My question is how to open a DialogFragment clicking on the TextView "click HERE to give a name to the task" placed next to "play" button.
Here is the code of my TextView:
TextView buttonView = new TextView(this);
buttonView.setHint("click HERE to give a name to the task");
buttonView.setX(50);
buttonView.setY(50);
and the code of the DialogFragent:
public class ButtonNameDialogFragment extends DialogFragment {
private IFragment iButNamFrag;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder setButNameAlert = new AlertDialog.Builder(getActivity());
setButNameAlert.setTitle("Set Task name");
LayoutInflater inflater = getActivity().getLayoutInflater();
setButNameAlert.setView(inflater.inflate(R.layout.button_name_fragment, null))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogPositiveClick
}
})
.setNegativeButton(R.string.undo, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Implement dialogNegativeClick
}
});
return setButNameAlert.create();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
iButNamFrag = (IFragment) activity;
}
}
and here is the interface:
public interface IFragment {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
You can set an onClickListener to any view in Android and then perform any behavior you would like
buttonView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Create new DiaglogFragment and display it
}
};
This is the same method used for any kind of button pressing. There are plenty of other answers already out on StackOverflow with further examples of this. If you need more information on tap recognition or displaying fragments, a quick search will find it on Stack.
buttonView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment frag = new ButtonNameDialogFragment();
frag.show(*context*, ButtonNameDialogFragment.class.getCanonicalName());
}
});

Button crashes on second click, removeView() exception

When I click the calculate button for the first time it works fine but on the second click after the Result Dialog has been dismissed the app crashes.logcat shows the error The specified child already has a parent. You must call removeView on the child's parent first. What should I do now? and how do I add the removeView?
public class MainActivity extends Activity {
float Remaining,Departure,TotUplift,SG,DiscResult;
int CalUpliftResult;
TextView RemainingTV,DepartureTV,UpliftTV,SGtv,CalcUpliftTV,DiscrepancyTV,resultOne,resultTwo;
EditText RemainingET,DepartureET,TotUpliftET,SGet,CalcUpliftET,DiscrepancyET;
Button calculateButton,okButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupView();
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
alert.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});
}
I fixed it, the alertdialog must be created inside the onclick of the calculate button, so that each time I click it, the dialog gets created all over again thus preventing interference from previous dialog values. here's the corrected code segment:
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if(validationET())
{
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
LayoutInflater factory = LayoutInflater.from(context);
final View textEntryView = factory.inflate(R.layout.dialog,null);
resultOne=(TextView)textEntryView.findViewById(R.id.resultOne); //resultone is a textview in xml dialog
resultTwo=(TextView)textEntryView.findViewById(R.id.resultTwo);
alert.setTitle("RESULT");
alert.setIcon(R.drawable.ic_launcher);
alert.setView(textEntryView);
alert.setNeutralButton("OK",null);
getETvalue();
evaluation();
CalcUpliftTV.setText(String.valueOf(CalUpliftResult));
DiscrepancyTV.setText(String.valueOf(DiscResult));
resultOne.setText("Calc. Uplift (KG)= "+String.valueOf(CalUpliftResult));
resultTwo.setText("Discrepancy(%)= "+String.valueOf(DiscResult));
AlertDialog alertD = alert.create();
alertD.show();
}
else
Toast.makeText(getApplicationContext(), "please give all inputs", Toast.LENGTH_SHORT).show();
}
});

Categories

Resources