Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - How to to fetch data from SQLite db in a separate thread and use it in the main thread callback?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create class thats implements Runnable

private class DataClass implements Runnable {

    private volatile List<T> data = new ArrayList<>();

    @Override
    public void run() {
        ...Background task...
        data = listFromDatabase;
    }

    public List<T> getData() {
        return data;
    }
}

And then use it like:

public List<T> getData() throws InterruptedException {
    DataClass dataClass = new DataClass();
    Thread thread = new Thread(dataClass);
    thread.start();
    thread.join();
    return dataClass.getData();
}

This is gonna wait value to be fetched and then return it's value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...