AseedUsmani AseedUsmani - 1 year ago 73
Android Question

Populate listView using handler or any other technique / update listView from outside onCreate

I have member variable String mActivity[] which gets updated every 3 seconds through a function onConnected. onCreate connects the API, (using Api.connect()).
I have to show the data saved in mActivity, but I cannot update data from outside onConnect.

How to use handler or any other technique to update listView?

Full code is too long to post - so I'm posting snippets.

protected void onCreate(Bundle savedInstanceState) {

String variable is declared as a member variable.

public void onConnected(@Nullable Bundle bundle) {
Intent intent = new Intent(this, ActivityRecognizedService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 3000, pendingIntent);

onConnected calls ActivityRecognizedService which changes values of mActivity[] (by making an object of the Activity); hence values of mActivity changes every 3 seconds. I need to update this in listView.

Answer Source

Add the new entries to your array, then call notifyDataSetChanged() on your adapter to update the ListView.

I would need to see more of your code to give an exact answer, but, for example, you could do something like this:

private void refreshListView(List<String> newEntries) {
    yourList.clear(); // yourList is the List that has the data for your adapter
    yourList.addAll(newEntries); // refresh the data with the new entries
    yourAdapter.notifyDataSetChanged(); // yourAdapter is the adapter for your ListView

You can call this method from anywhere in your class.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download