显示空数据的房间。复杂数据有问题

时间:2018-11-16 13:38:26

标签: java android android-room

我是Android架构组件的新手,并且一直在尝试从服务器存储数据的空间。问题是没有数据显示在回收站视图中,并且我认为问题在于将数据插入数据库中,因为我能够使用翻新功能从我的API中检索数据,而从数据库中记录数据则显示为空。任何建议高度赞赏!

API的Pojo餐厅: RestaurantsModel.java

餐厅实体: Restaurant.java

位置实体(这是@嵌入餐厅实体): Location.java

所有这些类型/类都在使用类似的DataTypeConverters:

MenuTypeConverter.java

RestaurantDao.java:

@Dao
public interface RestaurantDao {

@Insert(onConflict = OnConflictStrategy.REPLACE)
void saveAll(List<Restaurant> restaurants);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void save(Restaurant restaurants);

@Update
void update(Restaurant restaurants);

@Delete
void delete(Restaurant restaurants);

@Query("SELECT * FROM Restaurant")
LiveData<List<Restaurant>> findAll();

@Query("SELECT COUNT(*) FROM Restaurant")
int totalRestaurants();
}

RestaurantsDatabase.java(我还尝试将对象添加到仍未显示的数据库中):

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


private static RestaurantsDatabase INSTANCE;

private final static List<Restaurant> RESTAURANTS = Arrays.asList(
        new Restaurant("Winterlympics", "Norway's", "He finished","`1AM",
                "6AM","d", "of", 2, 2, 4,
                2, 2,4,4,null,"p",null,
                new Location("USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA"),
                null,null,null,null,null),
        new Restaurant("Winterlympics", "NOway's", "04850568540","`1AM",
                "6AM","d", "of", 2, 2, 4,
                2, 2,4,4,null,"p",null,
                new Location("USA", "USA", "USA", "USA", "USA", "USA", "USA", "USA"),
                null,null,null,null,null)
);

public abstract RestaurantDao restaurantDao();

private static final Object sLock = new Object();

public static RestaurantsDatabase getInstance(Context context) {
    synchronized (sLock) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    RestaurantsDatabase.class, "Restaurants.db")
                    .allowMainThreadQueries()
                    .addCallback(new RoomDatabase.Callback() {
                        @Override
                        public void onCreate(@NonNull SupportSQLiteDatabase db) {
                            super.onCreate(db);
                            Executors.newSingleThreadExecutor().execute(
                                    () -> getInstance(context).restaurantDao().saveAll(RESTAURANTS));
                        }
                    })
                    .build();
        }
        return INSTANCE;
    }
}
}

RestaurantViewModel.java:

public class RestaurantViewModel extends AndroidViewModel {
private RestaurantDao restaurantDao;
private ExecutorService executorService;
private ApiInterface webService;

public RestaurantViewModel(@NonNull Application application) {
    super(application);
    restaurantDao = RestaurantsDatabase.getInstance(application).restaurantDao();
    executorService = Executors.newSingleThreadExecutor();
    webService = ApiClient.getApiClient().create(ApiInterface.class);
}

LiveData<List<Restaurant>> getAllRestaurants() {
    refreshUser();
    Log.d("TAG", "============ From DB: " + restaurantDao.findAll().getValue());
    return restaurantDao.findAll();
}

void saveRestaurant(Restaurant restaurant) {
    executorService.execute(() -> restaurantDao.save(restaurant));
}

void deleteRestaurant(Restaurant restaurant) {
    executorService.execute(() -> restaurantDao.delete(restaurant));
}

private void refreshUser() {
    executorService.execute(() -> {

        int numOfRestaurants = restaurantDao.totalRestaurants();
        // If user have to be updated
        if (numOfRestaurants < 30) {
            Call<RestaurantsModel> call = webService.getRestaurants("Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvb3Z0by5jb1wvYXBpXC9sb2dpbiIsImlhdCI6MTU0MjM2ODY4MiwiZXhwIjoxNTQyMzcyMjgyLCJuYmYiOjE1NDIzNjg2ODIsImp0aSI6Im1GSHM4WmNiUVN0TEdJRHMiLCJzdWIiOjEsInBydiI6IjIzYmQ1Yzg5NDlmNjAwYWRiMzllNzAxYzQwMDg3MmRiN2E1OTc2ZjcifQ.-w1bouh4ljb-kk5zsu1vfaOcIIpaHcCUps5y3KuY6bc");
            call.enqueue(new Callback<RestaurantsModel>() {
                @Override
                public void onResponse(@NonNull Call<RestaurantsModel> call, @NonNull Response<RestaurantsModel> response) {
                    restaurantDao.saveAll(response.body().getData().getData());
                }

                @Override
                public void onFailure(@NonNull Call<RestaurantsModel> call, @NonNull Throwable t) {
                    Log.d("TAG", "@Request onFailure " + t.toString());
                }
            });
        }
    });
}}

MainActivity:

public class MainActivity extends AppCompatActivity {
private RestaurantsAdapter restaurantsAdapter;
private RestaurantViewModel restaurantViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    restaurantsAdapter = new RestaurantsAdapter(this);

    restaurantViewModel = ViewModelProviders.of(this).get(RestaurantViewModel.class);
    restaurantViewModel.getAllRestaurants().observe(this, restaurants -> restaurantsAdapter.setData(restaurants));

    RecyclerView recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setHasFixedSize(true);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(restaurantsAdapter);
 }
}

适配器: RestaurantsAdapter

需要任何其他信息,请告诉我。感谢您阅读我的长篇文章...

0 个答案:

没有答案