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 :)