Button crashes on second click, removeView() exception - java

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();
}
});

Related

On clicking the button dialog is not visible

I have created the button but when I click on the button it is not showing my dialog.
The button is shown that it clicks but nothing appears. I am trying to show a ⚠ dialog
Here my code
XML
<Button
android:layout_width="wrap_content"
android:id="#+id/submitB"
android:layout_height="36dp"
android:layout_weight="1"
android:background="#drawable/option_button"
android:text="#string/submit" />
XML under the LinearLayout
JAVA
private Button submitB;
submitB = (Button) findViewById(R.id.submitB);
submitB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitTest();
}
});
}
private void submitTest()
{
AlertDialog.Builder builder = new AlertDialog.Builder(QuestionsActivity.this);
builder.setCancelable(true);
View view = getLayoutInflater().inflate(R.layout.alert_dialog_layout,null);
Button cancelB= view.findViewById(R.id.cancle);
Button confirmB= view.findViewById(R.id.confirmB);
builder.setView(view);
AlertDialog alertDialog= builder.create();
cancelB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Call show() on your alertDialog object
private void submitTest()
{
AlertDialog.Builder builder = new AlertDialog.Builder(QuestionsActivity.this);
builder.setCancelable(true);
View view = getLayoutInflater().inflate(R.layout.alert_dialog_layout,null);
Button cancelB= view.findViewById(R.id.cancle);
Button confirmB= view.findViewById(R.id.confirmB);
builder.setView(view);
AlertDialog alertDialog= builder.create();
cancelB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
It seems you are missing the show() method to show your Dialog.
I suggest you this syntax which I use to show an AlertDialog:
new AlertDialog.Builder(CompileModuleActivity.this)
.setTitle(getResources().getString(R.string.success))
.setMessage(myMessage)
.setIcon(R.drawable.ic_check)
.setCancelable(false)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
Of course you can create a NegativeButton or NeutralButton to make the dialog dismiss. I just put finish() for my purpose.

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/

call method of dialog from other activity

i have problem that i cannot call dialog method from another activity, the dialog get user input into sharedprefrnces
here my activity that i want check if theres stored sharedprefernce if not exist i want the dialog appear to get the user input and after i click ok its continue running the main activity
here the main
public class main extends Activity {
private Button button;
private EditText CardNumber;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkid();
}
});
}
public void checkid(){
File f = new File(
"/data/data/com.example.ahmed_samir.enjaz/shared_prefs/MyPrefs.xml");
if (f.exists())
Toast.makeText(OpreatorMobily.this, "exist:", Toast.LENGTH_LONG).show();
else {
NationalId na= new NationalId();
na.dialogmethod();
}
}
}
and here my second activity of dialog
public class NationalId extends Activity {
public static final String MyPREFERENCES = "MyPrefs";
public static final String Name = "nameKey";
SharedPreferences sharedpreferences;
final Context context = this;
private Button button;
private TextView result;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_national_id);
dialogmethod();
// components from main.xml
button = (Button) findViewById(R.id.button1);
result = (TextView) findViewById(R.id.tv1);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialogmethod();
}
});
}
public void dialogmethod(){
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.prompts, null);
android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
context);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userInput = (EditText) promptsView
.findViewById(R.id.editTextDialogUserInput);
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String n = userInput.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, n);
editor.commit();
// edit text
result.setText(userInput.getText());
Toast.makeText(NationalId.this, "saved:" + n, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
android.app.AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
You should not do this. A possible solution is to create a separate class which contains a static method for your dialog.
So in your activity you can call it like this:
Dialog myDialog = CustomDialog.createDialog(this);
myDialog.show();
Inside the static method:
public static Dialog createDialog(Context context) {
Dialog dialog = new Dialog(this);
//do all the initialization stuff
//return the dialog
return dialog;
}

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 .

Sending the data back to the activity from alertDialog

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.

Categories

Resources