Issue
i'm new to Room database but have been working on it for last 1.5 week. I have recently come across a problem.
I am unable to parse the size of the list of journeys. When I try it always return a 0 even if I use a global variable. This is due to the override method, I believe.
I am trying to get the variable numberOfJourneys = journeys.size
. Is there any way round this. Also this is in a fragment.
private JourneyDatabase db;
private List<Journey> journeys;
private int numberOfjourneys;
public void arrayAdapter(){
db = Room.databaseBuilder(getContext(), JourneyDatabase.class, "MyJourneyDatabase").build();
AsyncTask.execute(new Runnable() {
@Override
public void run() {
journeys = db.journeyDao().getAllJourneys();
// journeys.size returns the correct size all the time
}
});
numberOfJourneys = journeys.size();
// journeys.size() returns 0 all the time
for(int i=0; i<numberOfJourneys; i++){
listOfJourneys.add(String.format("Journey %d", i));
}
}
Solution
The AsyncTask
will execute on a separate thread. Your code will execute the AsyncTask and will immediately move on to the for
loop regardless of whether the AsyncTask finished its execution or not. I'll mention a few ways that you can handle this.
Method 1: You can move the for
loop inside the AsyncTask itself. This will ensure that the for loop will execute after the data is fetched from the db.
Method 2: Allow this query to be run on the UI thread. AFAIK, Room allows queries to be run on the UI thread if explicitly mentioned.
Method 3: Use a callback. After, the AsyncTask finishes, you can use a callback (implemented using an interface) which will let your activity/fragment know that the AsyncTask has finished and you can carry on with your work.
Answered By - Bilal Naeem
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.