I have a method in my Fragment
that fetches values from a local database and puts this data in RecyclerView
. The data fetching lasts long that retards UI, so I decide to put it in a separate thread. I want the separate thread to return a method call from my main thread.
What are the best practices to do this?
Edit
I want to elaborate on my question, because the feedback I receive is not solving my problem. I will keep my original question untouched and edit the code.
I want to call in my Fragment
a method that would fetch from an SQLite
database some data in a separate thread and, subsequently, call a callback in the main thread to make use of the fetched data to update the UI. The data will be used in ReciclerView
. The code equivalent, as I imagine it, should look like this:
private Context context;
private List<T> mData;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
context = getActivity();
//-----------------Thread starts here.-------------------------
List<T> threadData = getData();
private List<T> getData(){
List<T> returnList;
...Go in SQLite database (Context required) to populate returnList...
return returnList;
}
//-------Thread ends here and calls threadOnFinish() callback in the main thread--------
}
@Overwrite
private void threadOnFinish(List<T> threadData,...){
useData(threadData);
}
private void useData(List<T> newData){
mData = newData;
...Use data and update UI...
}
Please, help
question from:
https://stackoverflow.com/questions/65645665/how-to-to-fetch-data-from-sqlite-db-in-a-separate-thread-and-use-it-in-the-main 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…