2017-08-30 9 views
2

私はナビゲーションメニューを持っているナビゲーションメニューを持っています。それぞれのナビゲーションメニューでクリックすると、特定の断片が開きます。たとえば、単語のナビゲーションメニューをクリックすると、単語の項目表示にrecyclerViewの項目が表示されます。私はオフラインと外部のSQLiteデータベースからデータを取り出して、recyclerViewの項目に表示しています。現在は、読み込み速度のデータとアプリのパフォーマンスを向上させたいので、メインスレッドではなく、別のスレッドでデータを取得したいと考えています。しかし、私はこれを行う方法を知らない。コードで私を助けてください。私はインターネット上で同じテーマを読んだが、今でも私の問題がある。AsyncTaskを使用してsqliteデータベースからデータをロードし、recyclerviewアイテムを表示する

この

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(); 
     } 
    } 


} 

AllWordsFragment

であり、これは私の 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とバックグラウンドでこれを行うが、私はどのようにこれを行うのですか?コードで私を助けてください。 ありがとう

答えて

1

あなたのクラスの中AsyncTaskクラスを作成します。

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

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

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

}//asyncClass 

は、この行でonCreate()loadingWords()を呼び出す置き換えます

new WordLoaderTask().execute(); 

あなたは(何らかの理由やアプリを使用する方法のために)なって起動した場合あなたのListViewで重複して、do{}の中の最初の行にwordsLists.clear();を追加すると、loadingWords()メソッド

+1

ありがとうございます@ヤザン。 :)働いた。大いに感謝する。とても簡単 :)。ちょうどonPostExecuteの中で私のアダプタに通知するのを覚えていない。 –

0

このようにしてみてください

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(); 
     } 
    } 
} 
関連する問題