RecyclerView отображает данные через раз

102
07 августа 2019, 09:10

После обновления версии библиотек в build.gradle RecyclerView на api lvl 24+ отображает данные через раз, но на api lvl <24 всё работает стабильно. В чём может быть проблема? Заранее спасибо.

Метод для получения данных

private void setUpDB() {
    myRef.child(getIntent().getStringExtra(FActivity.TITLE)).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            iterable = dataSnapshot.getChildren().iterator();
            for (int i = 0; i < dataSnapshot.getChildrenCount(); i++) {
                DataSnapshot dataFormula = iterable.next();
                Formula formula = new Formula(dataFormula.getKey(), String.valueOf(dataFormula
                        .getValue()));
                listFormulas.add(formula);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "Failed to read value.", databaseError.toException());
        }
    });
}

Полный класс для лучшего понимания

public class CorrectListActivity extends AppCompatActivity {
String TAG = "CorrectListActivity";
RecyclerView recyclerView;
ArrayList<Formula> listFormulas;
private Iterator<DataSnapshot> iterable;
private DatabaseReference myRef;
private Realm mRealm;
private Realm mRealmForDel;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
    preferences = PreferenceManager.getDefaultSharedPreferences(this);
    if (preferences.getBoolean("cb_pref_dark_style", false)) {
        setTheme(R.style.darkTheme);
    } else {
        setTheme(R.style.AppTheme);
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_correct_list);
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = database.getReference();
    myRef.keepSynced(true);
    mRealm = Realm.getInstance(PhysicsApp.getConfigForFavorites());
    mRealmForDel = Realm.getInstance(PhysicsApp.getConfigForDelFormulas());

    listFormulas = new ArrayList<>();
    recyclerView = findViewById(R.id.correctList_recyclerView);
    setUpDB();
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setHasFixedSize(true);
    CorrectListAdapter adapter = new CorrectListAdapter(listFormulas, this);
    adapter.setCorrectListCallback(new CorrectListCallback() {
        @Override
        public void liked(int position) {
            Formula item = listFormulas.get(position);
            mRealm.beginTransaction();
            Favorite favorite = mRealm.createObject(Favorite.class);
            favorite.setSection(getIntent().getStringExtra(FActivity.TITLE));
            favorite.setName(item.getTitle());
            favorite.setFormula(item.getFormula());
            mRealm.commitTransaction();
        }
        @Override
        public void unLiked(int position) {
            Formula item = listFormulas.get(position);
            mRealm.beginTransaction();
            RealmResults<Favorite> favorites = mRealm.where(Favorite.class)
                    .equalTo("name", item.getTitle()).findAll();
            for (int i = favorites.size() - 1; i >= 0; i--) {
                if (favorites.get(i) != null) {
                    favorites.get(i).deleteFromRealm();
                }
            }
            mRealm.commitTransaction();
        }
        @Override
        public boolean getLikedState(int position) {
            Favorite favorite = mRealm.where(Favorite.class)
                    .equalTo("name",
                            listFormulas.get(position).getTitle())
                    .findFirst();
            return favorite != null;
        }
        @Override
        public void crossToggle(int position, boolean isDelete) {
            Formula item = listFormulas.get(position);
            if(isDelete){
                mRealmForDel.beginTransaction();
                DelFormula delFormula = mRealmForDel.createObject(DelFormula.class);
                delFormula.setParent(getIntent().getStringExtra(FActivity.TITLE));
                delFormula.setName(item.getTitle());
                mRealmForDel.commitTransaction();
            }else {
                mRealmForDel.beginTransaction();
                RealmResults<DelFormula> delFormulas = mRealmForDel.where(DelFormula.class)
                        .equalTo("name",
                                item.getTitle()).findAll();
                for (int i = delFormulas.size() - 1; i >= 0; i--) {
                    if (delFormulas.get(i) != null) {
                        delFormulas.get(i).deleteFromRealm();
                    }
                }
                mRealmForDel.commitTransaction();
            }
        }
        @Override
        public boolean getCrossState(int position) {
            DelFormula delFormula = mRealmForDel.where(DelFormula.class)
                    .equalTo("name",
                            listFormulas.get(position).getTitle())
                    .findFirst();
            return delFormula != null;
        }
    });
    recyclerView.setAdapter(adapter);


}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_correct_list, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.itemHelp:
            Intent intent = new Intent(this, HelpActivity.class);
            intent.putExtra(FActivity.TITLE,getIntent().getStringExtra(FActivity.TITLE));
            startActivity(intent);
            break;
    }
    return super.onOptionsItemSelected(item);
}
private void setUpDB() {
    myRef.child(getIntent().getStringExtra(FActivity.TITLE)).addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            iterable = dataSnapshot.getChildren().iterator();
            for (int i = 0; i < dataSnapshot.getChildrenCount(); i++) {
                DataSnapshot dataFormula = iterable.next();
                Formula formula = new Formula(dataFormula.getKey(), String.valueOf(dataFormula
                        .getValue()));
                listFormulas.add(formula);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "Failed to read value.", databaseError.toException());
        }
    });
}

Адаптер

public class CorrectListAdapter extends RecyclerView.Adapter<CorrectListAdapter.Holder> {
private ArrayList<Formula> listData;
private LayoutInflater inflater;
private CorrectListCallback callback;
private boolean isDelete;

public CorrectListAdapter(ArrayList<Formula> listData, Context context) {
    this.listData = listData;
    this.inflater = LayoutInflater.from(context);
}
public void setCorrectListCallback(CorrectListCallback callback ){
    this.callback = callback;
}
public boolean getLikedState(int position){
    return callback.getLikedState(position);
}
public boolean getCrossState(int position){
    return callback.getCrossState(position);
}
private void checkState(CrossView crossView, int position, Context context){
    if(!getCrossState(position)){
        crossView.cross(0);
        isDelete = false;
    }else {
        crossView.plus(0);
        crossView.setColor(ContextCompat.getColor(context, R.color.colorCorrect));
        isDelete = true;
    }
}
@Override
public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.correct_list_item, parent, false);
    return new Holder(view);
}
@Override
public void onBindViewHolder(final Holder holder, final int position) {
    Formula item = listData.get(position);
    holder.title.setText(item.getTitle());
    holder.starButton.setLiked(getLikedState(holder.getAdapterPosition()));
    holder.starButton.setOnLikeListener(new OnLikeListener() {
        @Override
        public void liked(LikeButton likeButton) {
            callback.liked(holder.getAdapterPosition());
        }
        @Override
        public void unLiked(LikeButton likeButton) {
            callback.unLiked(holder.getAdapterPosition());
        }
    });
    checkState(holder.crossButton, position, holder.context);
    holder.crossButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkState(holder.crossButton, position, holder.context);
            holder.crossButton.toggle();
            isDelete = !isDelete;
            if (isDelete){
                holder.crossButton.setColor(ContextCompat.getColor(holder.context, R.color.colorCorrect));
            }else {
                holder.crossButton.setColor(ContextCompat.getColor(holder.context, R.color.colorDelCross));
            }
            callback.crossToggle(holder.getAdapterPosition(), isDelete);
        }
    });
    if (item.getFormula().split("[=]")[0].contains("/")) {
        holder.doubleFractionView.setVisibility(View.VISIBLE);
        holder.fractionView.setVisibility(View.GONE);
        holder.stoFractionView.setVisibility(View.GONE);
        holder.doubleFractionView.setDoubleFraction(item.getFormula());
    } else if (item.getFormula().split("[=]")[1].contains("◤")
            || item.getFormula().split("[=]")[1].contains("◢")
            || item.getFormula().split("[=]")[1].contains("◇")) {
        holder.stoFractionView.setVisibility(View.VISIBLE);
        holder.doubleFractionView.setVisibility(View.GONE);
        holder.fractionView.setVisibility(View.GONE);
        holder.stoFractionView.setSTOFraction(item.getFormula());
    } else {
        holder.fractionView.setVisibility(View.VISIBLE);
        holder.doubleFractionView.setVisibility(View.GONE);
        holder.stoFractionView.setVisibility(View.GONE);
        holder.fractionView.setFraction(item.getFormula());
    }
}
@Override
public int getItemCount() {
    return listData.size();
}
class Holder extends RecyclerView.ViewHolder {
    private TextView title;
    private FractionView fractionView;
    private DoubleFractionView doubleFractionView;
    private STOFractionView stoFractionView;
    private LikeButton starButton;
    private CrossView crossButton;
    private Context context;
    Holder(View itemView) {
        super(itemView);
        title = itemView.findViewById(R.id.correctItem_title);
        fractionView = itemView.findViewById(R.id.correctItem_formula);
        doubleFractionView = itemView.findViewById(R.id.correctItem_doubleFormula);
        stoFractionView = itemView.findViewById(R.id.correctItem_STOFormula);
        starButton = itemView.findViewById(R.id.correctItem_star_button);
        crossButton = itemView.findViewById(R.id.sample_cross_view);
        context = itemView.getContext();
    }
}
READ ALSO
JavaFX приложение не запускается

JavaFX приложение не запускается

Проблема состоит в следующем, мой jar файл запускается в товарища на ноуте, а у меня нетВерсия jdk у нас одинаковая

107
Не работают аспекты

Не работают аспекты

Есть главный класс, который содержит конфигурацию бинов

101
Задача с собеседования Java

Задача с собеседования Java

Есть вот такое задание:

98
Потокобезопасность Collections.synchronizedList

Потокобезопасность Collections.synchronizedList

Какой смысл потокобезопасности CollectionssynchronizedList если ее все равно нужно синхронизировать при итерации

109