我想制作一个应用程序列表器应用程序,它通过包管理器通过 AsyncTask<Void, Void, List<PackageSummary>>
获取应用程序列表。嵌套在单例类中。但是,当且仅当我实现异步任务时,RecyclerView 才不会在第一次 OnCreate 时填充。
我确信我犯了一个愚蠢的错误和/或对 AsyncTask 和 RecyclerView 的理解不够好,但出于我的爱,我找不到问题的根源。
In my toy app repository为了便于说明,我准备了两个相对干净的分支:
- 在主线程中获取包,并在第一个 Oncreate (git_UI_thread) 上填充 recyclerview。
- 其中一个
AsyncTask<Void, Void, List<PackageSummary>>
类被称为。应用程序持久性尚未设置(故意),并且RecyclerView
仅在应用程序旋转后才会填充 (git_background_thread)。
对于那些不愿意点击上面的bitbucket链接的人,我的AsyncTask
内部的代码 fragment 看起来像这样:
@Override
protected void onPostExecute(List<SingletonPackageSummarySupplier.PackageSummary> packageSummaries) {
super.onPostExecute(packageSummaries);
isQueryingInProgress = false;
packageSummaryList = packageSummaries;
}
@Override
protected List<SingletonPackageSummarySupplier.PackageSummary> doInBackground(Void... voids) {
List<PackageSummary> installedPackages = new ArrayList<>();
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
List<ResolveInfo> resolveInfoList = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resolveInfoList) {
ActivityInfo activityInfo = resolveInfo.activityInfo;
installedPackages.add(new PackageSummary(resolveInfo.activityInfo));
}
return installedPackages;
}
这是我的主要 Activity OnCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
psList = SingletonPackageSummarySupplier.getInstance(context).getPackageSummaryListReadOnly();
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerViewLayoutManager = new LinearLayoutManager(context);
recyclerView.setLayoutManager(recyclerViewLayoutManager);
adapter = new AdapterApplist(context, psList);
recyclerView.setAdapter(adapter);
}
这就是获取单例的方式:
static SingletonPackageSummarySupplier instance;
public static SingletonPackageSummarySupplier getInstance(Context context) {
if (instance == null) {
instance = new SingletonPackageSummarySupplier(context);
} else{
instance.updateInstance(context);
}
return instance;
}
P.S.:我认为(但不确定)单例模式是合理的,以减少内存泄漏的变化。
P.S.2:我已经阅读了几个与此相关的问题,但没有一个有可接受/有效的解决方案。
最佳答案
有两个步骤:将数据更新到 AdapterApplist 并通知它。因此,您应该创建一个新方法,例如:
public void setData(List<SingletonPackageSummarySupplier.PackageSummary> list)
{ //reset your data ere
}
在 AdapterApplist 类中。然后,更新您的帖子:
@Override
protected void onPostExecute(List<SingletonPackageSummarySupplier.PackageSummary> packageSummaries) {
super.onPostExecute(packageSummaries);
isQueryingInProgress = false;
packageSummaryList = packageSummaries;
adapter.setData(packageSummaryList);
adapter.notifyDataSetChanged();
}
关于java - Android AsyncTask RecyclerView 不填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49402430/