14

I am quite new to Android development. Can someone let me know the relevant APIs to dynamically update a TextView (or entire screen )?

For example: I have a search application and I need to show the results as they are found rather than waiting for all results and then show.

2
  • You will need to have the search done in a separate thread most probably if you do not want the search to block your main application execution. Then get it to periodically update a container with new TextView objects. So you could have a linear layout which is empty and periodically call to the search thread to see what results it has and add them to your linear layout. Feb 2, 2011 at 10:41
  • Is your question still unanswered?
    – winklerrr
    Dec 21, 2016 at 22:21

5 Answers 5

26

There are a few steps and you didn't mention how much you know versus how much you don't.

Assuming your UI initial structure is defined in the res/layout and it includes a TextView somewhere, in your activity:

public void updateTextView(String toThis) {
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(toThis);
}
0
3

If you have a new text to set to the TextView, just call textView.setText(newText), where newText is the updated text. Call this method whenever newText has changed. Is that what you are looking for?

2
  • thanks hmm...that answers to some extent...but i need to maintain the old data also in addition to the newly coming data...how do i do it.. should i use list view...
    – prash
    Mar 21, 2011 at 7:27
  • @prash to keep track of the old data, you can use textView.getText(). First: CharSequence old = textView.getText();, then e.g. concat old and new data and set it back to the TextView: textView.setText(old + " " + new);
    – winklerrr
    Dec 21, 2016 at 22:40
2

If you are inside another thread, make sure you update the textview inside the UI thread.

private void updateTextView(final String s) {
    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView tv= (TextView) findViewById(R.id.tv);
            tv.setText("Text = "+s);
        }
    });

}
0
1

First, you need a list view, so

private volatile ArrayList<String>      searchResults;
ListView searchList = (ListView) findViewById(R.id.listYOURLISTVIEW);
listAdapter = new ArrayAdapter<String>(this, R.layout.blacklist, R.id.list_content, searchResults);  //blacklist is a layout to paint the fonts black
searchList.setAdapter(listAdapter);

Here's something that might help.

private Thread refreshThread;
private boolean isRefreshing = false;

private void reinitializeRefreshThread()
{
    if (!refreshThread.equals(null)) refreshThread.stop();
    Log.d(LOGTAG+"::reinitializeRefreshThread()", "Creating new thread!\n");
    isRefreshing = true;
    refreshThread = (new Thread(new Runnable()
    {
        public void run()
        {
            Looper.prepare();
            while (isRefreshing)
            {
                //GRAB YOUR SEARCH RESULTS HERE
                //make sure the methods are synchronized
                //maybe like 
                String[] results = grabResults(); //doesn't need to be synchronized
                addResultList(results);

                Message message = myHandler.obtainMessage();
                myHandler.sendMessage(message);
                try
                {
                    Thread.sleep(2000);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
                Log.d(LOGTAG+"->refreshThread", "Refresh finished!\n");
            }
        }
    }));
    Log.d(LOGTAG+"::reinitializeRefreshThread()", "Refresh thread started!\n");
    refreshThread.start();
}

final Handler myHandler = new Handler() 
{
    public void handleMessage(android.os.Message msg)   
    {
        listAdapter.notifyDataSetChanged();
    }; 
};

where

public synchronized void addResultList(String[] results)
{
    // remove the whole list, repopulate with new data
    searchResults.clear();
    for (int i = 0; i < results.length; i++)
    {
        addResult(results[i]);
    }
}

private synchronized void addResult(CharSequence result)
{
    if (!searchResults.contains(result.toString()))
        searchResults.add(result.toString());
    else
        Toast.makeText(getApplicationContext(), "Result " + result.toString() + " was already on the list!", Toast.LENGTH_SHORT).show();
}

All of this is thread-safe, meaning it will allow you to 'change' GUI from threads other than the main thread by sending the message to the main thread that the UI needs updating. As you can see, the refreshThread updates the search collection (make sure the method is synchronized) and later notifies the main (UI) thread to update the list.

You will probably find this useful too

searchList.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
        {
            listIndex = arg2;
            selectedItem = (String) searchList.getItemAtPosition(listIndex);
            Toast.makeText(getApplicationContext(), "Result[" + listIndex + "] " + selectedItem + " selected!", Toast.LENGTH_SHORT).show();
        }
    });

There might be a few loose ends such as you need to initialize listIndex and selectedItem or just throw em out, but in general this did the trick for me in a very similar situation (I have a background thread that populates a list over time with new entries)

Hope it helps :)

1

Try this one

TextView textView = (TextView)findViewById(R.id.textViewID);
textView.setText("The test you need");
view.invalidate();  // for refreshment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.