使用AsyncTask从sqlite数据库加载数据并在recyclerview项目中显示

时间:2017-08-30 08:15:43

标签: android android-asynctask android-sqlite

我有一个导航菜单,上面有导航菜单。单击每个导航菜单时,将打开特定片段。例如,当我单击单词导航菜单时,单词项目会显示recyclerView个项目。我从离线和外部SQLite数据库中获取数据并显示在recyclerView项目上。现在我想在另一个线程中获取数据,而不是在主线程中,因为我想提高加载速度数据和应用程序性能。但我不知道该怎么做。请帮我一个代码。我在互联网上阅读了相同的主题,但我现在仍然有我的问题。

这是我的 AllWordsFragment

public class AllWordsFragment extends Fragment {

private List<WordsList> wordsLists = new ArrayList<>();
private Cursor cursor;
ProgressBar progressBar;
RecyclerView recyclerView;
AllWordsAdapter allWordsAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.all_words_fragment, container, false);
    progressBar = view.findViewById(R.id.progressBar);
    progressBar.setMax(600);
    allWordsAdapter = new AllWordsAdapter(getActivity(), wordsLists);
    allWordsAdapter.notifyDataSetChanged();
    recyclerView = view.findViewById(R.id.recyclerViewAllWords);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setHasFixedSize(true);
    recyclerView.setAdapter(allWordsAdapter);
    loadingWords();

    return view;
}

private void loadingWords() {

    WordDatabase wordDatabase = new WordDatabase(getActivity());

    try {

        wordDatabase.createDatabase();
        wordDatabase.openDatabase();

    } catch (SQLiteException e) {
        e.printStackTrace();
    }


    try {

        cursor = wordDatabase.QueryData("SELECT Word, Definition, Example, WordList, ImageWord FROM Words");

        if (cursor != null && cursor.moveToFirst()) {

            do {

                WordsList wordList = new WordsList();
                wordList.setWordTitle(cursor.getString(0));
                wordList.setDefinition(cursor.getString(1));
                wordList.setExample(cursor.getString(2));
                wordList.setVocubList(cursor.getString(3));
                wordList.setImageWord(cursor.getString(4));
                wordsLists.add(wordList);


            } while (cursor.moveToNext());


            wordDatabase.close();
        }


    } catch (SQLiteException w) {
        w.printStackTrace();
    } finally {

        if (cursor != null) {
            cursor.close();
        }
    }


}

这是我的 AllWordsAdapter

公共类AllWordsAdapter扩展了RecyclerView.Adapter {

private int lastPosition = -1;
protected Context context;
private List<WordsList> wordsListList = new ArrayList<>();

public AllWordsAdapter(Context context, List<WordsList> wordsListList) {
    this.context = context;
    this.wordsListList = wordsListList;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View view = LayoutInflater.from(context).inflate(R.layout.all_words_item, parent, false);


    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    WordsList wordsList = wordsListList.get(position);
    holder.wordTitle.setText(wordsList.getWordTitle());
    holder.definitionWord.setText(Html.fromHtml(wordsList.getDefinition()));
    holder.exampleWord.setText(Html.fromHtml(wordsList.getExample()));
    holder.labelWordList.setLabelText(wordsList.getVocubList());


    //get image from assets with Glide.
    String pathImage = wordsList.getImageWord();
    String assetsPath = "file:///android_asset/";
    Glide.with(context)
            .asBitmap()
            .load(Uri.parse(assetsPath + "" + pathImage))
            .into(holder.wordImage);
    Log.d("path", assetsPath + "" + pathImage);

    Typeface headerFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Bold.ttf");
    holder.wordTitle.setTypeface(headerFont);

    Typeface customFont = Typeface.createFromAsset(context.getAssets(), "fonts/Roboto-Italic.ttf");
    holder.exampleWord.setTypeface(customFont);
    holder.definitionWord.setTypeface(customFont);

    //cal animation function
    setAnimation(holder.itemView, position);

    holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(context, AllWordsDetails.class);
            intent.putExtra("word", holder.wordTitle.getText().toString());
            context.startActivity(intent);
        }
    });


}

@Override
public int getItemCount() {
    return wordsListList.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    private CircleImageView wordImage;
    private LabelTextView labelWordList;
    private TextView wordTitle, definitionWord, exampleWord;

    private RelativeLayout relativeLayout;

    public ViewHolder(View itemView) {
        super(itemView);


        wordTitle = itemView.findViewById(R.id.allWordTitle);
        wordImage = itemView.findViewById(R.id.circleHeaderImage);
        exampleWord = itemView.findViewById(R.id.exampleAllWord);
        definitionWord = itemView.findViewById(R.id.definitionAllWord);
        labelWordList = itemView.findViewById(R.id.labelWordList);
        relativeLayout = itemView.findViewById(R.id.relativeAllWords);
    }
}

private void setAnimation(View viewToAnimation, int position) {
    // If the bound view wasn't previously displayed on screen, it's animated
    if (position > lastPosition) {

        ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimation.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
        viewToAnimation.startAnimation(scaleAnimation);
        lastPosition = position;
    }
}

}

我知道必须使用 AsyncTask 并在后台执行此操作,但我不知道这是怎么做到的?请帮我一个代码。 谢谢

2 个答案:

答案 0 :(得分:3)

在类中创建一个AsyncTask类:

class WordLoaderTask extends AsyncTask<Void, Void, Void> {

    protected Void doInBackground(Void... params) {
        loadingWords();
    }

    protected void onPostExecute(Void param) {
        allWordsAdapter.notifyDataSetChanged(); 
    }

}//asyncClass

使用以下行替换loadingWords()中的调用onCreate()

new WordLoaderTask().execute();

如果您(由于某种原因或某种方式使用应用)开始在ListView中获取重复项,请在wordsLists.clear();方法{/ 1}中的第一行添加do{}

答案 1 :(得分:0)

Try like this

public class AllWordsFragment extends Fragment {

    private List<WordsList> wordsLists = new ArrayList<>();
    private Cursor cursor;
    ProgressBar progressBar;
    RecyclerView recyclerView;
    AllWordsAdapter allWordsAdapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.all_words_fragment, container, false);
        progressBar = view.findViewById(R.id.progressBar);
        progressBar.setMax(600);
        allWordsAdapter = new AllWordsAdapter(getActivity(), wordsLists);
        allWordsAdapter.notifyDataSetChanged();
        recyclerView = view.findViewById(R.id.recyclerViewAllWords);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(allWordsAdapter);
        loadingWords();

        return view;
    }


    private static LoadWordsTask extends AsyncTask<Void, Void, List<WordsList>> {
        private Context context;
        private AllWordsAdapter adapter;
        private List<WordsList> wordsLists;

        public LoadWordsTask(Context context, AllWordsAdapter adapter, List<WordsList> wordsLists) {
            this.context = context;
            this.adapter = adapter;
            this.wordsLists = wordsLists;
        }

        @Override
        public List<WordsList> doInBackground() {
            List<WordsList> data = new ArrayList<>();

            WordDatabase wordDatabase = new WordDatabase(getActivity());

            try {

                wordDatabase.createDatabase();
                wordDatabase.openDatabase();

            } catch (SQLiteException e) {
                e.printStackTrace();
            }


            try {

                cursor = wordDatabase.QueryData("SELECT Word, Definition, Example, WordList, ImageWord FROM Words");

                if (cursor != null && cursor.moveToFirst()) {

                    do {

                        WordsList wordList = new WordsList();
                        wordList.setWordTitle(cursor.getString(0));
                        wordList.setDefinition(cursor.getString(1));
                        wordList.setExample(cursor.getString(2));
                        wordList.setVocubList(cursor.getString(3));
                        wordList.setImageWord(cursor.getString(4));
                        data.add(wordList);


                    } while (cursor.moveToNext());


                    wordDatabase.close();
                }


            } catch (SQLiteException w) {
                w.printStackTrace();
            } finally {

                if (cursor != null) {
                    cursor.close();
                }
            }

            return data;
        }


        @Override
        public void onPostExecute(List<WordsList> data) {
            this.wordsLists.addAll(data);
            this.adapter.notifyDataSetChanged();
        }
    }
}