Removed items reappear on Landscape

Asked

Viewed 53 times

0

I have a ArrayAdapter in a Listview and when the user clicks and holds it displays a Contextmenu with the Delete bookmark option.

The delete function is working, but as I create the Adapter in the onCreateView Every time I put it in Landscape the items come back because it recreates the View

I would like to know how to avoid this

Fragment that displays bookmarks

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.list_item, container, false);

        mAdapter = new FavoritosAdapter(getActivity(), carregarFavoritos());

        listView = (ListView) rootView.findViewById(R.id.list_favoritos);

        listView.setAdapter(mAdapter);

        registerForContextMenu(listView);

        listView.setEmptyView(rootView.findViewById(R.id.empty));

        return rootView;
    }


    public ArrayList<Favoritos> carregarFavoritos(){
         ArrayList<Favoritos> favoritos = new ArrayList<Favoritos>();
         favoritos.add(new Favoritos("endereco", 5, false, 7, 22));
         favoritos.add(new Favoritos("endereco", 3.5 , true, 7, 22));
         favoritos.add(new Favoritos("endereco", 2, false, 7, 22));
         favoritos.add(new Favoritos("endereco", 4.5, true, 7, 22));

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        if (v.getId() == R.id.list_favoritos) {
            //Outras opções
            menu.add(Menu.NONE, 3, Menu.NONE, R.string.txt_excluir);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
         final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
         switch (item.getItemId()) {
         //Função das outras opções
         case 3:
            favoritosExcluidos = favoritos.remove(info.position);
            mAdapter.notifyDataSetChanged();

            Snackbar snackbar = Snackbar.make(listView, R.string.txt_favorito_excluido, Snackbar.LENGTH_LONG);
            snackbar.setAction(R.string.txt_desfazer, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Favoritos favorito = favoritosExcluidos;
                    favoritos.add(info.position, favorito);
                    mAdapter.notifyDataSetChanged();
                }
            });
            snackbar.show();
            break;
    }
    return true;
}

Favoritosadapter

  public FavoritosAdapter(Context context, ArrayList<Favorito> favoritos){
    super(context, 0, favoritos);
}

public static class ItemViewHolder{
    TextView textView1;
    TextView textView2;
    TextView textView3;
    TextView textView4;
    TextView textView5;
    RatingBar ratingBar;
    ImageView imageView;
    TextView textView6;

    public ItemViewHolder(View view){
        textView1 = (TextView) view.findViewById(R.id.txt1);
        textView2= (TextView) view.findViewById(R.id.txt2);
        textView3= (TextView) view.findViewById(R.id.txt3);
        textView4= (TextView) view.findViewById(txt4);
        textView5= (TextView) view.findViewById(txt5);
        ratingBar= (RatingBar) view.findViewById(R.id.ratingBar);
        imageView= (ImageView) view.findViewById(R.id.img);
        textView6= (TextView) view.findViewById(R.id.txt6);
    }
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View listItemView = convertView;


    if (listItemView == null) {
        listItemView = LayoutInflater.from(getContext()).inflate(
                R.layout.favoritos_item, parent, false);
    }

    Favorito currentFavorito = getItem(position);

    final ItemViewHolder holder;

    if(listItemView.getTag() == null){
        holder = new ItemViewHolder(listItemView);
        listItemView.setTag(holder);
    } else {
        holder = (ItemViewHolder) listItemView.getTag();
    }

    if(currentFavorito.getBooleanTxt6()){
        holder.txt6.setText(currentFavorito.txt1());
    } else {
        holder.txt6.setText(currentFavorito.getTxt1());
    }
    holder.txt1.setText(currentFavorito.getTxt1());
    holder.txt2.setText(currentFavorito.getTxt2());
    holder.txt3.setText(currentFavorito.getTxt3());
    holder.txt4.setText(currentFavorito.getTxt4());
    holder.txt5.setText(currentFavorito.getTxt5());
    holder.ratingBar.setRating(currentFavorito.getAvaliacao());


    if(currentFavorito.getBooleanTxt6()){
        holder.imageView.setImageResource(R.drawable.img);
        holder.txt6.setText(R.string.txt6true);
        holder.txt6.setTextColor(getContext().getResources().getColor(R.color.verde));
    } else {
        holder.imageView.setImageResource(R.drawable.img2);
        holder.txt6.setText(R.string.txt6false);
        holder.txt6.setTextColor(getContext().getResources().getColor(R.color.vermelho));
    }

    return listItemView;
}
  • The Bundle passed as parameter in the onCreateView method behind the previous values, in case only check whether it is null or not.

1 answer

2


What happens is that you need to implement a fragment called onSaveInstanceState() and save all data that you do not want to be "recreated" when rotating the screen, for example. And then on onActivityCreated(), You get the data and you reuse it. Only that you would need to implement Parcelable in your class Favoritos.

The class Favoritos that I created further down is just one example, since I don’t know what your class is like.

Fragment.java

private static final String STATE_FAVORITOS = "stateFavoritos";

// Declara a lista como membro da classe
private List<Favoritos> favoritos;

public ArrayList<Favoritos> carregarFavoritos() {
    favoritos = new ArrayList<>();

    // Adiciona seus itens após instanciar sua lista
    favoritos.add(new Favoritos("endereco", 5, false, 7, 22));
    favoritos.add(new Favoritos("endereco", 3.5 , true, 7, 22));
    favoritos.add(new Favoritos("endereco", 2, false, 7, 22));
    favoritos.add(new Favoritos("endereco", 4.5, true, 7, 22));
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.list_item, container, false);

    // Instancia seu adapter sem a lista, primeiro
    mAdapter = new FavoritosAdapter(getActivity());

    listView = (ListView) rootView.findViewById(R.id.list_favoritos);

    listView.setAdapter(mAdapter);

    registerForContextMenu(listView);

    listView.setEmptyView(rootView.findViewById(R.id.empty));

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState == null) {
        carregarFavoritos();
    } else {
        favoritos = savedInstanceState.getParcelableArrayList(STATE_FAVORITOS);
    }

    // Não sei se você já tem esse método, mas talvez tenha que criar.
    // Não se esqueça de chamar notifyDataSetChanged() dentro desse método
    mAdapter.setFavoritos(favoritos);
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Passa a lista que você quer salvar
    savedInstanceState.putParcelableArrayList(STATE_FAVORITOS, (ArrayList<? extends Parcelable>) favoritos);

    super.onSaveInstanceState(savedInstanceState);
}

Java favorites.

// Sugiro fortemente a você alterar o nome da sua classe
// do plural para o singular, para evitar confusão no entendimento do código.
// E uma vez que ela, aparentemente, representa UM favorito
public class Favoritos implements Parcelable {
    private String endereco;
    private int numero;
    private boolean booleano;

    private Favoritos(Parcel in) {
        // Os mesmos membros passados aqui e também na mesma ordem
        // devem ser passados no método writeToParcel()
        endereco = in.readString();
        numero = in.readInt();
        booleano = in.readByte() != 0;
    }

    @Override
    public boolean equals(Object o) {
        if (getClass() != o.getClass()) return false;

        Favoritos that = (Favoritos) o;

        // Aqui você faz a comparação que achar necessário
        // para verificar se um Favoritos é igual a outro.
        // A que eu coloquei aqui é só um exemplo
        return this == that || (endereco == that.endereco && numero == that.numero);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(endereco);
        dest.writeInt(numero);
        dest.writeByte((byte) (booleano ? 1 : 0));
    }

    public static final Creator<Favoritos> CREATOR = new Creator<Favoritos>() {
        @Override
        public Favoritos createFromParcel(Parcel in) {
            return new Favoritos(in);
        }

        @Override
        public Favoritos[] newArray(int size) {
            return new Favoritos[size];
        }
    };
}

Favoritosadapter.java

private List<Favoritos> favoritos;

// Remova a sua lista de favoritos como parâmetro do construtor
public FavoritosAdapter(Context context) {
    // Remove a passagem de 'favoritos' como parâmetro do super também
    super(context, 0);
}

// Outros métodos
...

// Implemente esse método, já que a lista de favoritos
// não vai ser passada no super() desse adapter
@Override
public Favoritos getItem(int position) {
    return favoritos.get(position);
}

// Implemente esse método, já que a lista de favoritos
// não vai ser passada no super() desse adapter
@Override
public int getCount() {
    return favoritos == null ? 0 : favoritos.size();
}

public void setFavoritos(List<Favoritos> favoritos) {
    // Passa sua lista e notifica o adapter para 'inflar' as views
    this.favoritos = favoritos;
    notifyDataSetChanged();
}

public void remove(Favoritos favorito) {
    remove(favoritos.indexOf(favorito));
}

public void remove(int position) {
    if (position >= 0) {
        favoritos.remove(position);
        notifyDataSetChanged();
    }
}
  • in the part that creates the Adapterin the onCreateView he is giving an error asking to pass the list. It is also giving an error because the Favorites already implement Serializable there in a method putExtra, in the Fragment is giving ambiguity. And the method setFavoritosdoes not exist. How can I solve?

  • You can add the code of FavoritosAdapter to the question?

  • In the case of your class Favoritos, you would have to withdraw the implementation of Serializable. Parcelable does better and faster what Serializable ago.

  • I removed the implemetation of Serializable, but the error in creating the Adapter object continues

  • in the constructor it asks for a list as parameter

  • implementing only the inteface Parcelable i am no longer able to pass the data via Intent to the other Àctivity, como eu fazia com o Serializable. Tem como fazer iso com o Parcelable` also?

  • I updated the response with the changes and methods you would need to implement in your FavoritosAdapter. Regarding the Parcelable, yes, it is also used to pass data via intent. If you can explain exactly how you are passing the data to the fragment, I can update the reply too.

  • thank you very much! sorry the delay to test. I pass the data via intentin the onClickListener with the method putExtra

  • 1

    In that case, then it will work the same way: intent.putExtra("favoritoSelecionado", favorito). Just in time to get the Intent object back you will need to change from getSerializableExtra() for getParcelableExtra().

  • so that’s why I was giving NullPointerException, I didn’t even touch. thanks for the help brother!

  • We’re here to help ;D

  • Dude, I know it’s not the main question (and I’m sorry about that), but how do I make an item like this to be deleted once and not reappear either when putting in land or when reopening the app? I’d have to keep it in an external comic book or you could keep it in your own favoritos?

  • I believe that in order not to have problems with the rules of Stack Overflow, it is right to create a chat so as not to "pollute" the comments. There I can answer questions related to your question. https://chat.stackexchange.com/rooms/info/68457/itens-removals-reappear- ao-botar-em-lands?capetab=general

Show 8 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.