This is not a duplicated question, I've tried everything about this topic that appears on StackOverflow and nothing works.
The problem is that when I try to update a listview when added new data it don't show the updated data when calling notifyDataSetChanged(), I have to exit and enter again the Activity to see the changes in the ListView. Nothing works, even clearing the list and adding the new data again.
Don't worry about the http client, the problem is not there, it works perfectly. Replacing it with a "hand made" ArrayList shows the same problem. The loop is not the problem too, the same problem persist outside the loop.
public class CredentialManager extends AppCompatActivity implements View.OnClickListener {
final Handler handler = new Handler(Looper.getMainLooper());
ListView credentialsList;
ArrayList<String> credentials;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_credential_manager);
credentialsList = findViewById(R.id.credentialsList);
credentials = HTTPClientCredentials.read("findByUser", String.valueOf(MainActivity.user.getIdUser()));
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, credentials);
credentialsList.setAdapter(adapter);
adapter.notifyDataSetChanged();
handler.postDelayed(new Runnable() {
public void run() {
credentials.clear();
credentials = HTTPClientCredentials.read("findByUser", String.valueOf(MainActivity.user.getIdUser()));
adapter.notifyDataSetChanged();
handler.postDelayed(this, 5000);
}
}, 5000);
}
}
replace :
credentials.clear();
with :
adapter.clear()
and whenever you want adding data to the list use:
adapter.addAll(credentials)
or
adapter.insert("new data")
its must fix your problem.
last point : adapter.notifyDataSetChanged(); it not necessary because it is inside the body of adapter methods. good luck.