【问题标题】:Android - How to access data from the Room database to the Stack WidgetAndroid - 如何从 Room 数据库访问数据到 Stack Widget
【发布时间】:2019-09-21 06:40:35
【问题描述】:

我刚刚了解了 Android,在这里我有功课。我试图制作一个从数据库 Room 访问数据的堆栈小部件,在这里我尝试访问它但数据没有出现,我对解决方案感到困惑,仍然不明白

private Context context;
private List<MovieEntity> list = new ArrayList<>();

public StackRemoteViewsFactory(Context context) {
    this.context = context;
}

@Override
public void onCreate() {

}

@Override
public void onDataSetChanged() {
    new AsyncTask<Context, Void, List<MovieEntity>>() {

        @Override
        protected List<MovieEntity> doInBackground(Context... contexts) {
            AppDatabase database = AppDatabase.getInstance(context);
            list = database.favoriteDao().getMovies();

            return list;
        }

        @Override
        protected void onPostExecute(List<MovieEntity> movieEntities) {
            super.onPostExecute(movieEntities);
        }

    }.execute(context);
}

@Override
public RemoteViews getViewAt(int position) {
    RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.item_widget);

    for (MovieEntity movieEntity : list) {
        Bitmap bmp = null;
        try {
            bmp = Glide.with(context)
                    .asBitmap()
                    .load("https://image.tmdb.org/t/p/w300_and_h450_bestv2" + movieEntity.getPosterPath())
                    .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get();

        } catch (Exception e) {
            Log.d("ERROR", "error");
        }


        rv.setTextViewText(R.id.txt_item_title, movieEntity.getTitle());
        rv.setImageViewBitmap(R.id.image_item_poster, bmp);
    }
    return rv;

}

@Override
public int getViewTypeCount() {
    return 1;
}

【问题讨论】:

    标签: android android-widget android-room android-database


    【解决方案1】:

    问题是你没有使用onPostExecute()中的movieEntities列表

    AsyncTask 的工作方式是doInBackground() 用于执行实际的后台工作(网络访问、数据库访问等)。

    然后,您从此方法返回的任何内容都将传递给onPostExecute(),该onPostExecute() 在主线程上运行,然后您应该使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 2021-02-04
      • 2020-08-13
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      相关资源
      最近更新 更多