Delete TextView after posting a message

advertisements

After I press a button, a query is performed and data is returned if data is present or no data is returned. This data is then sent to my listview. If there are results in the query, everyting is working as expected. If no data is returned, I have a clause so that an TextView is created and a message is presented to the user.

Imagine I perform a query wen I press the button and no data is returned. My message is presented to the user as expected. If then I perform a query that returns some data, the message disappears and the listview is populated as expected. Now imagine that after the first query with no data (the message is presented to the user) I perform another another query that still returns no data. Message is presented (probably it's presented "above" the previous one) and if I now perform a query with data, my listview is populated but the message is still there.

Can someone explain me why is this happening and what can I do to, after a query with results, all previous no result messages disappear and the listview "alone"?

This is my code:

searchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //GETS THE DATA

            ListView listContent = (ListView) findViewById(android.R.id.list);
            MySimpleAdapt arrayListAdapter = new MySimpleAdapt(Search.this, allData);
            listContent.setAdapter(arrayListAdapter);

            if (allData.size() == 0) {
                TextView emptyView = new TextView(getApplicationContext());
                emptyView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                emptyView.setTextColor(Color.BLACK);
                emptyView.setText(R.string.notFound);
                emptyView.setPadding(4, 30, 4, 30);
                emptyView.setTextSize(30);
                emptyView.setVisibility(View.GONE);
                emptyView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

                if (getListView().getParent() != null) {
                    ((ViewGroup) getListView().getParent()).addView(emptyView);
                }
                getListView().setEmptyView(emptyView);
            }
        }
    });


There is no need to create your TextView each time you hit a situation when there is no data. Store it as a member in your class and initialize only once