简体   繁体   English

Android ListView notifyDataSetChanged() 不刷新列表

[英]Android ListView notifyDataSetChanged() dont refresh the list

This is not a duplicated question, I've tried everything about this topic that appears on StackOverflow and nothing works.这不是一个重复的问题,我已经尝试了 StackOverflow 上出现的关于这个主题的所有内容,但没有任何效果。

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.问题是,当我尝试在添加新数据时更新列表视图时,在调用 notifyDataSetChanged() 时它不显示更新的数据,我必须退出并再次进入活动以查看列表视图中的更改。 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.不用担心 http 客户端,问题不存在,完美运行。 Replacing it with a "hand made" ArrayList shows the same problem.用“手工制作”ArrayList 替换它会出现同样的问题。 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();最后一点:adapter.notifyDataSetChanged(); it not necessary because it is inside the body of adapter methods.它没有必要,因为它在适配器方法的主体内。 good luck.祝你好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM