我是 Android 开发新手,我已经开始创建这个应用程序,我在其中读取 XML 提要并列出内容。但即使提要发生变化,我仍然显示相同的数据。尽管一夜之间缓存似乎会自行清除。我想在每次启动应用程序时强制读取提要。我尝试了这里描述的方法 How to clear cache Android但这没有帮助。
我的猜测是我必须在主要 Activity 中的 onCreate 上执行此操作(至少这是我迄今为止尝试过的)。
有人能指出我正确的方向吗?
提前致谢:-)
这里是一些代码 fragment 。
来 self 的 Activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_game);
deleteCache(this);
new ReadLeagueXml().execute();
}
deleteCache 是我链接到的另一个线程的方法。
然后在我的 doInBackground 中我有
InputStream inputStream = new URL(xmlURL).openStream();
if (inputStream != null) {
list = parse(inputStream);
}
最后在我的 onPostExecute 中:
ListView matchListView = (ListView)findViewById(R.id.match_list);
List<String> matchArray = new ArrayList<String>();
for (int i = 0; i < matches.size(); i++) {
matchArray.add(matches.get(i).HomeTeam + " - " + matches.get(i).AwayTeam);
}
matchArray.toArray();
matchesArrayAdapter = new MatchListAdapter(ListGameActivity.this, matches);
matchListView.setAdapter(matchesArrayAdapter);
最佳答案
你的代码看起来非常好。您也不需要“清除缓存”。
现在回到问题,如果我正确理解你的问题,提要没有刷新。这是因为您在 onCreate()
上下载了新数据。因此,当您第一次启动应用程序时,就会下载数据。然后用户转到另一个应用程序(请记住 Android 不会关闭您的 Activity,它只会暂停它)。因此,当用户回来时,如果应用程序未关闭,Android 将恢复它!因此您的 onCreate()
将不会再次被调用。
简而言之,
更新 onResume()
中的数据,每次向用户显示您的 Activity 时都会调用该数据。将 new ReadLeagueXml().execute();
移至 onResume()
,每次用户打开应用程序时都会下载新数据。
您可能想查看 Android Activity 生命周期 here
关于android - 如何清除android缓存onCreate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14920015/