我正在尝试在我的应用程序中实现小部件。该小部件将显示从Firebase获取的乐谱列表。
问题是在列表为空的getViewAt()
之前调用onDataSetChanged()
方法。
调用onDataSetChanged()
之后,即使我用按钮强制刷新,也永远不会再次调用getViewAt()
。
我该如何做?
我尝试了几种在线找到的解决方案,但似乎这里缺少某些东西。
这是我的课程,扩展了RemoteViewsFactory
public class WidgetDataProvider implements RemoteViewsService.RemoteViewsFactory {
private List<Scores> scoresList = new ArrayList<>();
String userId;
DatabaseReference childNode;
Context mContext;
Intent intent;
WidgetDataProvider(Context mContext, Intent intent) {
this.mContext = mContext;
this.intent = intent;
}
@Override
public void onCreate() {
initializeData();
}
@Override
public void onDataSetChanged() {
initializeData();
}
@Override
public void onDestroy() {
scoresList.clear();
}
@Override
public int getCount() {
return scoresList.size();
}
@Override
public RemoteViews getViewAt(int index) {
RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.scores_widget_item);
remoteViews.setTextViewText(R.id.tv_scores_widget_item, scoresList.get(index).getCategoryName());
remoteViews.setTextViewText(R.id.tv_scores_widget_item_score, scoresList.get(index).getCategoryScore()* 10 + "%");
return remoteViews;
}
@Override
public RemoteViews getLoadingView() {
return null;
}
@Override
public int getViewTypeCount() {
return 1;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
private void initializeData() throws NullPointerException {
try {
scoresList.clear();
assert FirebaseAuth.getInstance().getCurrentUser() != null;
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
childNode = FirebaseDatabase.getInstance().getReference(DATA_SCORES).child(SCORES_BY_USER).child(userId);
childNode.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (final DataSnapshot category : dataSnapshot.getChildren()) {
scoresList.add(new Scores(userId, category.getKey(), Integer.parseInt(category.child(SCORE).getValue().toString())));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}catch (NullPointerException e){
Log.d("firebase_exception", "initializeData: " + e.getMessage());
}
}
}