The specified child already has a parent. You must call removeView() on the child's parent first (Android)

In my app, I have to switch between two layouts frequently. The error is happening in the layout posted below.

When my layout is called the first time, there isn't occuring any error and everything's fine. When I then call a different layout (a blank one) and afterwards call my layout a second time, it gives me the following error:

> FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

My layout-code looks like this:

    tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code


private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

I know this question has been asked before, but it didn't help in my case.

Answers


The error message says what You should do.

// TEXTVIEW
if(tv.getParent()!=null)
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

Need Your Help

A good algorithm similar to Levenshtein but weighted for Qwerty keyboards?

algorithm string text comparison

I noticed some posts here on string matching, which reminded me of an old problem I'd like to solve. Does anyone have a good Levenshtein-like algorithm that is weighted toward Qwerty keyboards?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.