Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

You must call removeView() on the child's parent first with AlertView

I have a alert dialog and i will get text with TextView but When I call it a second time, the app crashes with error:

04-15 19:37:48.433: E/AndroidRuntime(907): java.lang.IllegalStateException: 
    The specified child already has a parent. You must call removeView() on 
    the child's parent first.

My Java source:

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final RelativeLayout rLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
        Button btn1 = (Button) findViewById(R.id.button1);
        final AlertDialog.Builder build = new AlertDialog.Builder(MainActivity.this);
        build.setTitle("Ders Adı Giriniz");
        final EditText dersAdiGir = new  EditText(MainActivity.this);
        build.setView(dersAdiGir);
        final LinearLayout layoutDers = (LinearLayout) findViewById(R.id.layoutDers);

        build.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                Editable girilenDers = dersAdiGir.getText();
                TextView tv1 = new TextView(MainActivity.this);
                tv1.setText(girilenDers);
                layoutDers.addView(tv1);
                dialog.dismiss();
                build.create();

            }
        });

        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                AlertDialog alert = build.create();
                alert.show();
            }
        });




    }
}

Please help me, thanks all

like image 743
Furkan KELES Avatar asked Apr 15 '15 21:04

Furkan KELES


1 Answers

You're creating a new instance of the AlertDialog every button click. Create a final AlertDialog outside of the OnClickListener inner class.

Here's the fix:

final AlertDialog alert = build.create();
btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        alert.show();
    }
});
like image 97
Gready Avatar answered Oct 28 '22 02:10

Gready