How to pass data from activity or fragment to viewmodel? - java

I am creating a project in which i am using themoviedb api to fetch data. For this I am using MVVM architecture. From MovieListFragment , I want to pass category such as popular, top_rated to MovieViewModel for filtering the movies accordingly , but there i am getting null value.
Here is MovieListFragment class :-
public class MovieListFragment extends Fragment {
private MovieViewModel movieViewModel;
private static final String BASE_URL = "https://api.themoviedb.org";
private static final String API_KEY = "API_KEY";
private String category;
private GridView gridView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movie_list, container, false);
gridView = rootView.findViewById(R.id.images_grid_view);
movieViewModel = ViewModelProviders.of(this).get(MovieViewModel.class);
movieViewModel.setCategory(category); // from here i am passing value
movieViewModel.getMoviesRepository().observe(getActivity(), new Observer<MovieResults>() { // error line no :- 76
#Override
public void onChanged(MovieResults movieResults) {
final List<MovieResults.ResultsBean> listOfMovies = movieResults.getResults(); // error line no :- 79
MovieListAdapter mAdapter = new MovieListAdapter(getContext(), listOfMovies);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCallback.onImageSelected(position, listOfMovies);
}
});
}
});
return rootView;
}
public void setCategory(String category) {
this.category = category;
}
}
Here is MovieViewModel class :-
public class MovieViewModel extends AndroidViewModel {
private String category;
private static final String API_KEY = "api_key";
private MovieRepository repository;
private MutableLiveData<MovieResults> listOfMovies;
public MovieViewModel(#NonNull Application application) {
super(application);
Log.d("MovieViewModel", category); // but here i am getting null value
listOfMovies = repository.getListOfMovies(category, API_KEY);
}
public MutableLiveData<MovieResults> getMoviesRepository() {
return listOfMovies;
}
public void setCategory(String category) {
this.category = category;
}
}
I am getting error like this :-
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.mountblue.moviesapp.entity.MovieResults.getResults()' on a null object reference
at com.mountblue.moviesapp.fragment.MovieListFragment$2.onChanged(MovieListFragment.java:79)
at com.mountblue.moviesapp.fragment.MovieListFragment$2.onChanged(MovieListFragment.java:76)

Since the Category is read by the constructor of MovieViewModel before the setter, it is always null.
What about category as method arguments?
public class MovieViewModel extends AndroidViewModel {
private static final String API_KEY = "api_key";
private MovieRepository repository;
private MutableLiveData<MovieResults> listOfMovies = new MutableLiveData<MovieResults>();
public MovieViewModel(#NonNull Application application) {
super(application);
}
public MutableLiveData<MovieResults> getMoviesRepository(category) {
loadData(category);
return listOfMovies;
}
private void loadData(category) {
// Do an asynchronous operation to fetch MovieResults.
repository.getListOfMovies(category, API_KEY);
...
// Receive asynchronous result in callback
// Post the result after getting the asynchronous result.
listOfMovies.postValue(response)
}
}
For a more detailed implementation, need a repository class.
Documents:
https://developer.android.com/topic/libraries/architecture/viewmodel

If you are getting null value for the string category in line movieViewModel.setCategory(category);, it means the field category of MovieListFragment is null.
Try checking if you have invoked the setCategory(String category) method on the fragment.
If that's not the case, please elaborate on the error. E.g. on which line it occurs etc.

In MovieListFragment class:
First delete this line: movieViewModel.setCategory(category);
And pass "category" here: movieViewModel.getMoviesRepository(category)
like code below:
movieViewModel.getMoviesRepository(category).observe(getActivity(), new Observer<MovieResults>() { // error line no :- 76
#Override
public void onChanged(MovieResults movieResults) {
final List<MovieResults.ResultsBean> listOfMovies = movieResults.getResults(); // error line no :- 79
MovieListAdapter mAdapter = new MovieListAdapter(getContext(), listOfMovies);
gridView.setAdapter(mAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCallback.onImageSelected(position, listOfMovies);
}
});
}
});
In MovieViewModel class:
Move this line inside getMoviesRepository(String category) listOfMovies = repository.getListOfMovies(category, API_KEY);
And just remove category variable and setCategory() method from MovieViewModel class like this:
public class MovieViewModel extends AndroidViewModel {
private static final String API_KEY = "api_key";
private MovieRepository repository;
private MutableLiveData<MovieResults> listOfMovies;
public MovieViewModel(#NonNull Application application) {
super(application);
}
public MutableLiveData<MovieResults> getMoviesRepository(String category) {
Log.d("MovieViewModel", category); // but here i am getting null value
listOfMovies = repository.getListOfMovies(category, API_KEY);
return listOfMovies;
}
}

Related

Data not displaying through ViewModel

I am newbie to android development and not able to understand why the data is being not displayed. initially the lists are empty so it should show empty text view but it is not showing that also.
Here's the code
Viewmodel factory
public class ViewModelFactoryListItFragment implements ViewModelProvider.Factory {
String category;
Application application;
public ViewModelFactoryListItFragment(Application application,String category ) {
this.category = category;
this.application = application;
}
#NonNull
#Override
public <T extends ViewModel> T create(#NonNull Class<T> aClass) {
if (aClass.isAssignableFrom(ViewModelListItFragment.class)) {
return (T) new ViewModelListItFragment(application, category);
} else throw new IllegalArgumentException("Viewmodel not found");
}
}
ViewModel
public class ViewModelListItFragment extends ViewModel {
private AppDatabase mDb;
private LiveData<List<ListItEntry>> myEntries;
private Application mApplication;
private String mCategory;
public ViewModelListItFragment(#NonNull Application application, String category) {
this.mCategory = category;
this.mApplication = application;
mDb = AppDatabase.getInstance(mApplication);
myEntries = mDb.listItDao().getListItsByCategory(mCategory);
}
public LiveData<List<ListItEntry>> getMyEntries() {
return myEntries;
}
}
Fragment
public class ListItFragment extends Fragment {
private FragmentListItBinding mBinding;
private ViewModelListItFragment mViewModel;
private String mCategory;
public ListItFragment(String category) {
super();
this.mCategory = category;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Timber.i("List it fragment created");
mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_list_it, container, false);
ViewModelFactoryListItFragment factoryListItFragment = new ViewModelFactoryListItFragment(this.getActivity().getApplication(), mCategory);
mViewModel = new ViewModelProvider(this, factoryListItFragment).get(ViewModelListItFragment.class);
LiveData<List<ListItEntry>> entries = mViewModel.getMyEntries();
entries.observe(this.getViewLifecycleOwner(), listItEntries -> {
if(listItEntries == null || listItEntries.size() == 0){
mBinding.textEmpty.setVisibility(View.VISIBLE);
mBinding.recyclerView.setVisibility(View.INVISIBLE);
}
mBinding.textEmpty.setVisibility(View.INVISIBLE);
mBinding.recyclerView.setVisibility(View.VISIBLE);
});
return mBinding.getRoot();
}
I have not yet implemented recylerview adapter so it will not show existing data but when the entries are not there then also it is not showing empty textView.
entries.observe(this.getViewLifecycleOwner(), listItEntries -> {
if(listItEntries == null || listItEntries.size() == 0){
mBinding.textEmpty.setVisibility(View.VISIBLE);
mBinding.recyclerView.setVisibility(View.INVISIBLE);
} else {
mBinding.textEmpty.setVisibility(View.INVISIBLE);
mBinding.recyclerView.setVisibility(View.VISIBLE);
}
});
Your code is outside if part thus even though your condition is met the part outside your if is being executed. Add an else part to make sure that it doesn't get executed as shown above

How to update complex recyclerview item parameters?

here is my post item:
public class PostItems {
private String id_wall_post, id_user, text_wall_post, ..........;
public PostItems(String id_wall_post, String id_user, String text_wall_post, ..............) {
this.id_wall_post = id_wall_post;
this.id_user = id_user;
this.text_wall_post = text_wall_post;
}
String get_id_wall_post() {
return id_wall_post;
}
String get_id_user() {
return id_user;
}
String get_text_wall_post() {
return text_wall_post;
}
...
...
.........
...
...
}
Here my adapter:
public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private List<PostItems> postList;
private Context context;
PostAdapter(List<PostItems> postList, Context context) {
this.postList = postList;
this.context = context;
}
#NonNull
#Override
public PostViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_view_wall_post, parent, false);
return new PostViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull PostViewHolder holder, int position) {
PostItems post_items = postList.get(position);
...
...
.........
...
...
}
#Override
public int getItemCount() {
return postList.size();
}
static class PostViewHolder extends RecyclerView.ViewHolder {
PostViewHolder(#NonNull View itemView) {
super(itemView);
}
}
}
Using retrofit the recyclerview is populated correctly:
postList.addAll(response.body());
postAdapter = new PostAdapter(postList, ProfileActivity.this);
recyclerView.setAdapter(postAdapter);
I also have an Editext where user can update the value of text_wall_post; I want now to update the item parameter text_wall_post of the recyclerView ?
How could I update a recyclerView item specific parameter ?
EDIT:
I have found that:
postList.set(1, new PostItems("1","1176", "some text update here", ..................));
postAdapter.notifyItemChanged(1);
In my recyclerView, I have more than 20 parameters.
Which work but I want a more clean way to update only the needed parameter without updating all the parameters.
Thanks for Any help.
You can change an item without creating a new one.
First make setters (like the getters you made) to change a specific parameter from an object(postItems in this case)
public class PostItems {
private String id_wall_post, id_user, text_wall_post, ..........;
public PostItems(String id_wall_post, String id_user, String text_wall_post, ..............) {
this.id_wall_post = id_wall_post;
this.id_user = id_user;
this.text_wall_post = text_wall_post;
}
String get_id_wall_post() {
return id_wall_post;
}
String get_id_user() {
return id_user;
}
String get_text_wall_post() {
return text_wall_post;
}
public void setIdWallPost(String idWallpost){
this.id_wall_post = idWallpost;
}
public void setIdUser(String idUser){
this.id_user = idWallUser;
}
public void setTextWallPost(String textWallPost){
this.text_wall_post = textWallPost;
}
...
...
.........
...
...
}
You can also make android studio generate them for you by pressing Alt+Inser > Setter
Then get the item with specific position from postList and update the parameter you want
postList.get(position).setTextWallPost("new value here");
And finally call
postAdapter.notifyItemChanged (position)

App Not Retrieving Documents From Firestore

I wanted to fetch some documents in a collection. The document should fetch name and specialty from a document. But each time I run the app, the documents are fetched and shown in the recyclerView as a list (just like in WhatsApp messenger), but the fields are not showing in by TextViews. That is the RecyclerView view display blank lists of `CardView with no texts ( ie the name and specialty I wanted it to display)
Below is the code for the Model, Adapter, and Activity:
THE MODEL
public class Doctor {
private String name;
private String DoctorImageURL;
private String specialty;
public Doctor() {
//empty constructor needed
}
public Doctor(String name, String specialty) {
this.name = name;
this.specialty = specialty;
}
public String getmDoctorName() {
return name;
}
public String getmDoctorSpecialty() {
return specialty;
}
THE ADAPTER
public class DoctorAdapter extends FirestoreRecyclerAdapter<Doctor, DoctorAdapter.DoctorHolder> {
public DoctorAdapter(#NonNull FirestoreRecyclerOptions<Doctor> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull DoctorHolder doctorHolder, int i, #NonNull Doctor doctor) {
doctorHolder.Name.setText(doctor.getmDoctorName());
doctorHolder.Specialty.setText(doctor.getmDoctorSpecialty());
//doctorHolder.DocImage.setImageResource(unifiedModel.getmDoctorImageURL());
//Load images here
}
#NonNull
#Override
public DoctorHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctor_list_view_items,
parent, false);
return new DoctorHolder(view);
}
class DoctorHolder extends RecyclerView.ViewHolder{
TextView Name, Specialty;
ImageView DocImage;
public DoctorHolder(#NonNull View itemView) {
super(itemView);
Name = itemView.findViewById(R.id.doctor_name);
Specialty = itemView.findViewById(R.id.doctor_specialty);
DocImage = itemView.findViewById(R.id.doctor_image);
}
}
THE ACTIVITY
public class DoctorActivity extends AppCompatActivity {
FirebaseAuth firebaseAuth;
private FirebaseFirestore rootReference = FirebaseFirestore.getInstance();
private CollectionReference doctorRef = rootReference.collection("doctor");
private DoctorAdapter doctorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor);
firebaseAuth = FirebaseAuth.getInstance();
setUpRecyclerView();
}
private void setUpRecyclerView() {
// Query FireStore and order items by name in Ascending order
Query query = doctorRef.orderBy("name", Query.Direction.ASCENDING);
FirestoreRecyclerOptions<Doctor> options = new FirestoreRecyclerOptions.Builder<Doctor>()
.setQuery(query, Doctor.class)
.build();
doctorAdapter = new DoctorAdapter(options);
RecyclerView recyclerView = findViewById(R.id.doctor_recycler_view);
recyclerView.setHasFixedSize(true); // For performance reasons
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(doctorAdapter);
}
#Override
protected void onStart() {
super.onStart();
doctorAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
doctorAdapter.stopListening();
}
}
this is the result:
Picture of my database structure
The problem in your code lies in the fact that you have wrong names for your getters in your Doctor class. You have defined the following fields:
private String name;
private String specialty;
With the corresponding getters:
public String getmDoctorName() {
return name;
}
public String getmDoctorSpecialty() {
return specialty;
}
Which is not correct. You getters should be named exactly as your fields. Please see the correct naming:
public String getName() {
return name;
}
public String getrSpecialty() {
return specialty;
}
Regarding the last one:
private String DoctorImageURL;
There is no value in your database. Besides that, your property starts with a capital letter which might lead to some other issues like:
Images not loading from URL by Picasso from Firebase Database
Or
Firebase Android ListView not being displayed

How to add elements to a list from another class?

So i have my a list on my main activity that i want to be able to access in another class. The second class is supposed to add more records to the list based on the users input but i don't know how to access it. Can anybody help?
Contactos.java:
This is my main class and its also where the list is kept, i did a test run on it so that's why the constructor is filled with numbers. I want to be able to add to the list from another class.
public class Contactos extends AppCompatActivity {
private Button btnReciente;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnReciente = (Button) findViewById(R.id.Reciente);
listView = (ListView) findViewById(R.id.list1);
List<contactosLista> list1 = new ArrayList<contactosLista>();
list1.add(new contactosLista("1","2","3","4","5","6"));
ContactosAdapter adapter = new ContactosAdapter(this,list1);
listView.setAdapter(adapter);
ContactosAdapter.java: This is where i inflate the list, i use it so i can use a .xml file to better display the values in the list.
public class ContactosAdapter extends BaseAdapter
{
private Context mContext;
private List<contactosLista>mListaContactos;
public ContactosAdapter(Context context, List<contactosLista> list)
{
mContext = context;
mListaContactos = list;
}
#Override
public int getCount() {
return mListaContactos.size();
}
#Override
public Object getItem(int position) {
return mListaContactos.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
contactosLista entrada = mListaContactos.get(position);
if(convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.contactos_row,null);
}
TextView Contact = (TextView) convertView.findViewById(R.id.Contacto);
Contact.setText(entrada.getmName() + " -- " + entrada.getmEmpresa());
return convertView;
}
}
contactosLista.java: This the class that defines the elements that the list needs. i made a constructor that accommodates all the strings and made all the setters & getters
public class contactosLista
{
private String mName;
private String mEmpresa;
private String mRazon;
private String mDireccion;
private String mEstatus;
private String mPaquete;
public contactosLista(String mName, String mEmpresa, String mRazon, String mDireccion, String mEstatus, String mPaquete)
{
this.mName = mName;
this.mEmpresa = mEmpresa;
this.mRazon = mRazon;
this.mDireccion = mDireccion;
this.mEstatus = mEstatus;
this.mPaquete = mPaquete;
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmEmpresa() {
return mEmpresa;
}
public void setmEmpresa(String mEmpresa) {
this.mEmpresa = mEmpresa;
}
public String getmRazon() {
return mRazon;
}
public void setmRazon(String mRazon) {
this.mRazon = mRazon;
}
public String getmDireccion() {
return mDireccion;
}
public void setmDireccion(String mDireccion) {
this.mDireccion = mDireccion;
}
public String getmEstatus() {
return mEstatus;
}
public void setmEstatus(String mEstatus) {
this.mEstatus = mEstatus;
}
public String getmPaquete() {
return mPaquete;
}
public void setmPaquete(String mPaquete) {
this.mPaquete = mPaquete;
}
}
createContact.java: finally this is the class where i want to be able to access the list from Contactos.java, I have a layout file that has a bunch of Edit text so that i can record input from the user. When the user clicks on the button to save i want my void "GuardarCon" to save the input from the user to strings and then i want to use those strings as parameters for my list. This is where the problem arises, i don't know how to call the list. PLS help.
public class createContact extends AppCompatActivity
{
EditText nombre;
EditText empresa;
EditText razon;
EditText direccion;
EditText estatus;
EditText paquete;
String snombre;
String sempresa;
String srazon;
String sdireccion;
String sestatus;
String spaquete;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_contact);
nombre = (EditText) findViewById(R.id.nombreT);
empresa = (EditText) findViewById(R.id.empresaT);
razon = (EditText) findViewById(R.id.razonSocialT);
direccion = (EditText) findViewById(R.id.direccionT);
estatus = (EditText) findViewById(R.id.EstatusT);
paquete = (EditText) findViewById(R.id.paqueteT);
}
public void GuardarCon(View view)
{
snombre = nombre.getText().toString();
sempresa = empresa.getText().toString();
srazon = razon.getText().toString();
sdireccion = direccion.getText().toString();
sestatus = estatus.getText().toString();
spaquete = paquete.getText().toString();
}
Create a singleton class and access and modify data as you want !
public class DataHolder{
public static final DataHolder instance = new DataHolder();
private List<Your_Data_Type> data;
//Your methods goes here...
}
You could use startActivityForResult method to start createContact from Contactos activity and after the addition process is done use setResult method to return the added item to the Contactos activity and handle adding the item to the list in onActivityResult.
take a look at this link for further info:
https://developer.android.com/training/basics/intents/result

Can't pre-populate Room database and see it on RecyclerView

I am trying to develop an application that uses Room Persistence Database and displays a list on a RecyclerView, I've followed Google's tutorials and everything but I can seem to see the items on the screen, the app doesn't crash or anything just nothing appearing on the scree:
Here is the Data object class:
#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;
}
Here is the Data Dao:
#Dao
public interface RegionDao {
#Query("SELECT * FROM region")
List<Region> getAll();
#Insert
void insert(Region... region);
#Query("DELETE FROM region")
void deleteAll();
Here is the Adapter Class:
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();
}
And this is the fragment that it is supposed to show the data base on:
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;
}
This is the AppDatabase Class:
#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();
}
};
And finally the AsyncClass to pre populate the database:
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;
}
if your id is PrimaryKey(autoGenerate = true), then don't set id in constructor.
update your onCreateView , you are use wrong database.
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

Categories

Resources