无法预先填充Room数据库并在RecyclerView上查看

时间:2018-05-29 09:13:58

标签: java android android-room

我正在尝试开发一个使用Room Persistence Database并在RecyclerView上显示列表的应用程序,我已经关注了Google的教程和所有内容,但我似乎可以看到屏幕上的项目,应用程序不会崩溃或什么都没有出现在碎石上:

这是Data对象类:

@Entity(tableName = "region")
public class Region {
@NonNull
@PrimaryKey(autoGenerate = true)
private int mId;

@ColumnInfo(name = "region_name")
private String mRegionName;

@ColumnInfo(name = "association")
private String mAssociation;

@ColumnInfo(name = "season")
private String mSeason;

public Region(@NonNull int id, String regionName, String association, String season) {
    mId = id;
    mRegionName = regionName;
    mAssociation = association;
    mSeason = season;
}


@NonNull
public int getId() {
    return mId;
}

public void setId(@NonNull int id) {
    mId = id;
}

public String getRegionName() {
    return mRegionName;
}

public void setRegionName(String regionName) {
    mRegionName = regionName;
}

public String getAssociation() {
    return mAssociation;
}

public void setAssociation(String association) {
    mAssociation = association;
}

public String getSeason() {
    return mSeason;
}

public void setSeason(String season) {
    mSeason = season;
}

这是Data Dao:

@Dao
public interface RegionDao {
@Query("SELECT * FROM region")
List<Region> getAll();

@Insert
void insert(Region... region);

@Query("DELETE FROM region")
void deleteAll();

这是适配器类:

public class RegionsAdapter extends RecyclerView.Adapter<RegionsAdapter.RegionViewHolder> {
private List<Region> mRegionList;
private Context mContext;
private int mRowLayout;
private RecyclerViewClickListener mListener;

public static class RegionViewHolder extends RecyclerView.ViewHolder{
    LinearLayout regionLayout;
    TextView regionName, regionAss, regionSeason;

    public RegionViewHolder(View v, RecyclerViewClickListener listener){
        super(v);
        regionLayout = v.findViewById(R.id.region_layout);
        regionName = v.findViewById(R.id.region_name);
        regionAss = v.findViewById(R.id.region_ass);
        regionSeason = v.findViewById(R.id.region_season);
    }
}

public void setClickListener(RecyclerViewClickListener recyclerViewClickListener){
    mListener = recyclerViewClickListener;
}

public RegionsAdapter(List<Region> regionList, Context context, int rowLayout, RecyclerViewClickListener listener) {
    mRegionList = regionList;
    mContext = context;
    mRowLayout = rowLayout;
    mListener = listener;
}

@Override
public RegionsAdapter.RegionViewHolder onCreateViewHolder(ViewGroup parent,
                                                                  int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(mRowLayout, parent, false);
    final RegionsAdapter.RegionViewHolder holder = new RegionsAdapter.RegionViewHolder(view, mListener);
    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mListener.onClick(v,holder.getLayoutPosition());
        }
    });
    return holder;
}

@Override
public void onBindViewHolder(RegionViewHolder holder, final int position){
    holder.regionName.setText(mRegionList.get(position).getRegionName());
    holder.regionSeason.setText(mRegionList.get(position).getSeason());
    holder.regionAss.setText(mRegionList.get(position).getAssociation());
}

@Override
public int getItemCount() {

    return mRegionList.size();
}

这是它应该显示数据库的片段:

public class RegionFragment extends Fragment {

private List<Region> mRegionList;
private RecyclerView mRecyclerView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.region_fragment, container, false);
    //whenever the activity is started, it reads data from database and stores it into
    // local array list 'mRegionList'
    final AppDatabase db = Room.databaseBuilder(getActivity().getApplicationContext(),
            AppDatabase.class,"app_database").allowMainThreadQueries().build();
    List<Region> regionList = db.getRegionDao().getAll();
    // Initializing the RecyclerView
    mRecyclerView = view.findViewById(R.id.region_rv);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
    RegionsAdapter adapter = new RegionsAdapter(regionList, getActivity().
            getApplicationContext(), R.id.region_layout, new RecyclerViewClickListener() {
        @Override
        public void onClick(View view, int position) {
            // Handling what happenes when a card is clicked
            // TODO handling
        }
    });
    mRecyclerView.setAdapter(adapter);
    return view;
}

这是AppDatabase类:

@Database(entities = {Region.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

public abstract RegionDao getRegionDao();

private static AppDatabase sInstance;

static AppDatabase getDatabase(final Context context) {
    if (sInstance == null) {
        synchronized (AppDatabase.class){
        if (sInstance == null) {
            sInstance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class,
                    "database").addCallback(sRoomDatabaseCallback).build();
        }
        }
    }
    return sInstance;
}




private static RoomDatabase.Callback sRoomDatabaseCallback =
        new RoomDatabase.Callback() {
            @Override
            public void onOpen(@NonNull SupportSQLiteDatabase db) {
                super.onOpen(db);
                new PopulateDbAsync(sInstance).execute();
            }
        };

最后是预先填充数据库的AsyncClass:

class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

private final RegionDao mDao;

PopulateDbAsync(AppDatabase db) {
    mDao = db.getRegionDao();
}

@Override
protected Void doInBackground(final Void... params) {
    mDao.deleteAll();
    Region region = new Region(0,"Europe","UEFA","2017/2018");
    mDao.insert(region);
    region = new Region(1, "Americas","CONCACAF","2017/2018");
    mDao.insert(region);
    region = new Region(2, "Asia","AFC","2017/2018");
    mDao.insert(region);
    region = new Region(3, "International","FIFA","2017/2018");
    mDao.insert(region);
    region = new Region(4, "Other","ConIFA","2017/2018");
    mDao.insert(region);
    return null;
}

1 个答案:

答案 0 :(得分:0)

如果您的ID为PrimaryKey(autoGenerate = true),则不要在构造函数中设置id。

更新您的onCreateView,您使用的是错误的数据库。

 final AppDatabase db =AppDatabase.getDatabase(getActivity());
List<Region> regionList = db.getRegionDao().getAll();// here you have fire your query in background thread. you can search for that