Alertdialog closing automatically after seconds? - java

I have implemented a Alertdialog, but this dialog closes automatically after 1 second. He doesn't even pay attention to the buttons, but simply closes automatically. I can't find the error in the code, do you perhaps know where my error is?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText name = new EditText(MainActivity.this);
builder.setTitle("Title");
builder.setMessage("Message");
builder.setPositiveButton("Ok", null);
builder.setNegativeButton("Cancel", null);
builder.setView(name);
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Button btnOK = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button btnCancel = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
btnOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = name.getText().toString();
if (name.isEmpty() || name.matches("")) {
name.setError("ERROR");
} else {
SharedPreferences.Editor editor;
editor = sharedPreferences.edit();
editor.putString("NAME", name);
editor.apply();
//Switch to next activity
}
}
});
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
}
});
dialog.show();

What is wrong?
There is nothing wrong in the code. But I have a suspicion on the code you have given.
How to correct?
Instead of adding clickListeners on btnOk and btnCancel inside the onShownListener, you can add then outside the onShow method. It will not make any difference but I feel that that was closing the dialog.That is why I feel you shall try what I have mentioned.

Related

Can't receive data from button Listener

I want to make button when I click on it a dialog appears and I read data from that dialog. In the dialog I have only EditText for data. My data is numbers.
Here is my code:
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
//if (savingsDialog.getText().toString().length() > 0) { I tried this if, but I receive empty data
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));// here I want to put my data in method which update my TextView
//}
}
});
Method(if you need it)
public void updateSavingsView(int savings){
TextView savingsTextView = (TextView) findViewById(R.id.saverTextView);
savingsTextView.setText("Save " + savings + "% per month");
TextView monthlySavings = (TextView) findViewById(R.id.savingsMoney);
if(savings == 0 || Integer.parseInt(income.getText().toString()) == 0 ) {
monthlySavings.setText("0");
}
else{
monthlySavings.setText(Integer.toString((Integer.parseInt(income.getText().toString()) * savings) / 100));
}
So the problem is that when I run program without if statement I have an error java.lang.NumberFormatException: For input string: "" . It is because it reads empty string and want to parse it. Then I add if statement to avoid this problem but it doesn't work.
And my question is. How I can rewrite this listener to avoid these problems and to store correct data?
Put your code inside the positive listener
Button mSaveButton = (Button) findViewById(R.id.saveButton);
mSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(ReportActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_for_percent , null);
final EditText savingsDialog = (EditText) mView.findViewById(R.id.percentEditText);
mBuilder.setView(mView)
.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Context context = getApplicationContext();
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
SharedPreferences savings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = savings.edit();
editor.putString("percent", savingsDialog.getText().toString());
editor.commit();
updateSavingsView(Integer.parseInt(savingsDialog.getText().toString()));
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
});

Hide Custom Dialog on button click

Currently I am using the following code and created a custom dialog. And dialog opens when button is clicked,, but I want to hide the dialog by tapping on OK button..but its not working and not showing error...
I used 'dialog.dissmis'
Code is here:
final Dialog dialog =new Dialog(ActionBarActivity. this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_dictionary);
TextView word = (TextView)dialog.findViewById(R.id.txtWord);
final TextView wordMeaning = (TextView)dialog.findViewById(R.id.txtMeaning);
dialog.getWindow().getAttributes().windowAnimations = R.style.AnimLeftRight;
//Get Words and it's meanings.
word.setText(Dictionary.getWord());
wordMeaning.setText(Dictionary.getMeaning());
Button btntts = (Button)dialog.findViewById(R.id.btntts);
final Button ok = (Button)dialog.findViewById(R.id.btnPositive);
// Show the dialog first.
dialog.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
dialog.getWindow().setAttributes(lp);
btntts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String convertTextToSpeech
wordMeaning.getText().toString();
convertToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
convertToSpeech.setLanguage(Locale.US);
convertToSpeech.speak(convertTextToSpeech, TextToSpeech.QUEUE_FLUSH, null, null);
}
}
});
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
});
Please anyone help me to hide the dialog on button click..thanks
This is the proper way to code a custom dialog box.
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
View builderView = getLayoutInflater().inflate(R.layout.custom_alert_view, null);
//Set the layout inside of the builder
builder.setView(builderView);
//Show the dislog
final AlertDialog alert = builder.show();
//Get Button from the layout.
Button dismiss = (Button) builderView.findViewById(R.id.dismiss);
//Click the dismiss button from within the alert. will dismiss the dialog box
dismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alert.dismiss();
}
});

alertDialog not showing when creating cancel button

I think I know where exactly is the problem but I don't know if I'm right or not and I don't know how to fix it
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View view1 = getActivity().getLayoutInflater().inflate(R.layout.dialog_reserv_table, null);
builder.setView(view1);
final AlertDialog dialog = builder.create();
Button annulerButton = (Button) view1.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
dialog.show();
I think creating dialog it should be after all declarations and before show
in this way
AlertDialog dialog=builder.create();
dialog.show();
but in this way I can't call dialog.cancel();
You can create a custom Dialog without AlertDialog.Builder:
Edit:
Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_reserv_table);
Button annulerButton=(Button)dialog.findViewById(R.id.annulerReserv);
annulerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.cancel();
}
});
dialog.show();
Source: http://www.mkyong.com/android/android-custom-dialog-example/

Can't add OnClickListener to a Button in a Dialog

I have written a function to handle showing of Dialog but I am not able to use OnClickListener in it. What is wrong with my code can any one tell me?
Here is my function
private void showInputDialog() {
final Dialog dialog=new Dialog(MainDashboard.this);
dialog.setContentView(R.layout.frg_dialog_change_pass);
btn_save_password=(Button) findViewById(R.id.btn_save_password);
btn_cancel_pass=(Button) findViewById(R.id.btn_cancel_pass);
edtOldpass=(EditText) findViewById(R.id.edtOldpass);
edtNewpass=(EditText) findViewById(R.id.edtNewpass);
edtConfirmpass=(EditText)findViewById(R.id.edtConfirmpass);
dialog.show();///Show the dialog.
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainDashboard.this, "Success", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}
Calling Activity.findViewById() will look for the View in the layout of your Activity (the one you've set by calling setContentView() in onCreate()).
I guess those Views are in your Dialog layout, so you need to call findViewById() on your Dialog instance:
btn_save_password = (Button) dialog.findViewById(R.id.btn_save_password);
btn_cancel_pass = (Button) dialog.findViewById(R.id.btn_cancel_pass);
edtOldpass = (EditText) dialog.findViewById(R.id.edtOldpass);
edtNewpass = (EditText) dialog.findViewById(R.id.edtNewpass);
edtConfirmpass = (EditText) dialog.findViewById(R.id.edtConfirmpass);
// Declare this globally above oncreate
private android.app.AlertDialog dialog;
android.app.AlertDialog.Builder alertDialog = new android.app.AlertDialog.Builder(MainDashboard.this);
LayoutInflater layoutInflater = getLayoutInflater();
View alertView = layoutInflater.inflate(R.layout.frg_dialog_change_pass, null);
alertDialog.setView(alertView);
alertDialog.setCancelable(false);
Button btn_save_password= (Button) alertView.findViewById(R.id.btn_save_password);
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do your stuff here
}
});
if(dialog !=null)
dialog.dismiss();
dialog = alertDialog.create();
dialog.show();
Change your function to:
private void showInputDialog() {
final Dialog dialog=new Dialog(MainDashboard.this);
View view = LayoutInflater.from(MainDashboard.this).inflate(R.layout.frg_dialog_change_pass);
dialog.setContentView(view);
btn_save_password=(Button) view.findViewById(R.id.btn_save_password);
btn_cancel_pass=(Button) view.findViewById(R.id.btn_cancel_pass);
edtOldpass=(EditText) view.findViewById(R.id.edtOldpass);
edtNewpass=(EditText) view.findViewById(R.id.edtNewpass);
edtConfirmpass=(EditText)view.findViewById(R.id.edtConfirmpass);
dialog.show();///Show the dialog.
btn_save_password.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainDashboard.this, "Success", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
}
Basically you have to use findViewById with the view which is used for dialog .

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