2017-08-30 4 views
2

J'ai un menu de navigation avec le menu nav dessus. Lorsque vous cliquez sur chaque menu de navigation, le fragment spécifique est ouvert.Par exemple, lorsque je clique sur le menu Mots nav, l'élément de mots s'affiche avec recyclerView éléments dessus. Je récupère des données à partir de base de données SQLite déconnecté et externe et affiche sur recyclerView éléments. Maintenant, je veux récupérer des données dans un autre thread, PAS dans le thread principal, car je veux augmenter les données de vitesse de chargement et les performances de l'application. Mais je ne sais pas comment faire ça. aidez-moi s'il vous plaît avec un code. J'ai lu le même sujet sur Internet, mais j'ai encore mon problème.Chargement des données de la base de données sqlite avec AsyncTask et affichage à l'intérieur des éléments de reclassement

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


} 

et ceci est mon AllWordsAdapter

public class AllWordsAdapter étend 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; 
    } 
} 

}

Je sais doit être utiliser AsyncTask et le faire en arrière-plan, mais je ne sais pas comment faire cela? S'il vous plaît aidez-moi avec un code. Merci.

Répondre

1

créer une classe AsyncTask dans votre classe:

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

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

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

}//asyncClass 

remplacer l'appel loadingWords() à onCreate() avec cette ligne:

new WordLoaderTask().execute(); 

si vous (pour une raison ou une façon d'utiliser l'application) commencer à obtenir duplique dans votre ListView, puis ajoute wordsLists.clear(); en tant que première ligne à l'intérieur du do{} en loadingWords() méthode

+1

Merci cher @Yazan. :) travaillé. Merci beaucoup. Si facile :). juste je ne me souviens pas notifier mon adaptateur à l'intérieur onPostExecute. –

0

Essayez comme ceci

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