Issue
I'm trying to get access into my database in the background so that i don't lock the threads and get an error, so i read i should use AsyncTask. from what i read up on it takes uses 3 data types. The data type it takes in, the data type it processes, and the return data type. so here im making a step tracker and want to access my database to get something by id, so i call my repository and pass in the database i'm using and the id i want to find
cStep = stepRepository.getStepById(stepDatabase,0);
and this here is my repository class and the AsyncTask within it
> public class StepRepository implements IStepDataSource {
private IStepDataSource mLocalDataSource;
private static StepRepository mInstance;
public StepRepository(IStepDataSource mLocalDataSource) {
this.mLocalDataSource = mLocalDataSource;
}
public static StepRepository getInstance(IStepDataSource mLocalDataSource){
if(mInstance == null)
mInstance = new StepRepository(mLocalDataSource);
return mInstance;
}
@Override
public Flowable<List<Step>> getAllSteps() {
return mLocalDataSource.getAllSteps();
}
@Override
public Step getStepById(StepDatabase db, int userId) {
return new getAsyncTask(db).execute(userId);
}
private static class getAsyncTask extends AsyncTask<Integer, Void, Step> {
getAsyncTask(StepDatabase db) {
this.db = db;
}
@Override
protected Step doInBackground(Integer... params) {
StepDao dao = db.stepDao();
return dao.getStepById(params[0]);
}
@Override
protected void onPostExecute(Step step) {
}
}
@Override
public void insertStep(Step... steps) {
mLocalDataSource.insertStep(steps);
}
@Override
public void updateStep(Step... steps) {
mLocalDataSource.updateStep(steps);
}
@Override
public void deleteStep(Step step) {
mLocalDataSource.deleteStep(step);
}
}
im not getting why getUserByid is giving me imcopatible type since AsyncTask takes in and interger and returns a steps which is what i want??
btw if its any help this is the IStepDataSource my repository implements
public interface IStepDataSource {
Flowable<List<Step>> getAllSteps();
Step getStepById(StepDatabase db, int userId);
void insertStep(Step... steps);
void updateStep(Step... steps);
void deleteStep(Step step);
}
Solution
The execute() method of AsyncTask returns void and your are attempting to return a void from a method declared as returning Step. It's probably best to get the AsyncTask out of the getStepById() method and instead use an AsyncTask where you invoke getStepById(). I think you're assuming that execute() blocks until the task is complete and that is incorrect. If this were the case, there'd be no point to using AsyncTask. execute() returns immediately and onPostExecute(Step step) is where the results should be processed/displayed/whatever.
Answered By - Greg Moens
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.