How to delete a specific Listview item?

Asked

Viewed 4,442 times

7

I would like to ask a question: I have one ListView, in which his Adapter is clarified in the same Activity and the content of Adapter (as strings) are in another class, in another package. How do I delete a specific item from ListView, same code, no user interaction? (for example, an application update where an item will no longer appear).

In the case I am studying, the user will click on an item from listView, and a string inside Activity will be filled with the string in otherClass.lista and depending on the position (position) clicked, a different text will appear.

EDITED

Follow the Listview click action:

ListView listView = (ListView) findViewById(R.id.lista);
listView.setAdapter(new listAdapter(this));

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {

                nome.setText(otherClass.string.get(position));

            }
});

Follow the Adapter I’m using:

public class listAdapter extends BaseAdapter implements ListAdapter {

    public Context context;
    public ArrayList<String> lug;
    public Typeface fonte;

    public listAdapter(Context context) {



        lug = otherClass.string;


        this.context = context;
    }

    @Override
    public int getCount() {
        return lug.size();
    }

    @Override
    public Object getItem(int position) {
        return lug[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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

            TextView title = new TextView(context);     
            title.setText(lug.get(position));
            title.setTextSize(18);

        return title;
    }

}

Now follow the Array in the class that is in another package

public class otherClass {

public static ArrayList<String> string = new ArrayList<String>();{
    string.add("primeiro item");
    string.add("Segundo item");
}
} 

The current problem is that the Arraylist items above are not being printed... and I would like to know (when to print the items) how to delete the items.

The intention, as follows the images, would be that in the otherClass have the items that will appear on listView and clicking on some item will appear the respective information of the clicked item (these declared in the same class not to get confused all separate). More items will be added to each app update, so it needs to be a dynamic and organized mode. Ideas? (since Strings doesn’t seem like a good shape)

Como quero que apareça a lista de itens 1Clicando em um dos itens anteriores, aparecerá outros itens, carregados naquela mesma classe "otherClass"

  • I think you want your getItem(position) return lug[position] and not position.

  • @Piovezan: 'position' is a global variable, being a reference for several other activities. In this case, position has the same function as lug[position], because they are the same numbers always. (in case I understood what you meant)

  • An Adapter is a class that mediates access to ListView to the data source, which can be an array, a database cursor, etc. The method getItem(position) you have to return an item within that data source that is in the position corresponding to the parameter position. Therefore, if your data source is an array or an Arraylist, which are already naturally ordered, your method getItem(position) must return meuArray[position] or minhaLista.get(position), representing items from these data sources in the position in question.

  • In addition, the position will never be the same as the item in that position, unless you have an array of integers and the value of each item matches the position in which it is in the array. So I don’t understand what you mean by position being the same as lug[position], because you’re dealing with strings and not integers. Do you mean that the items in the array are "0", "1", "2", etc.? In this case getItem(position) should return String.valueOf(position) and not position. But for all intents and purposes, return lug[position] makes more sense.

  • @Piovezan: I updated the code with more information. I used lug[position]. In my string, the items they are identified by the same position: "first item" = 0, "second item" = 1, and etc. take a look please. What I put as an update is the original mode with which I made the application, ran beautiful but the only thing is that I do not know delete the items, which maybe as they said there is as if it is declared as string[], correct?

  • See my comment below the reply.

  • I advise you to rephrase your question. Putting the code of each class and showing exactly where the error is, is very confusing the way it is, even following the comments.

  • @Lucassantos: Reformulated, are you less confused? I tried to dry up..

  • Enter your Activity code. You’re getting better. I’ll help you.

  • @Lucassantos: I forgot to put as I declared the Adapter and the Listview.. but it is practically just that my Activity..

  • @GH_ Ok, I’ll try to post a solution even without the Activity code. Wait I’m posting...

Show 6 more comments

2 answers

4


Come on @GH_ see if this helps.

Create a class called Others, this class will persist the data you want for a particular object, let’s assume it is a person, car, or anything. In your case will persist two Strings: first item and second item.

/**
 * Classe que irá persistir dados de um objeto para ser usado em uma lista de Strings.
 */
public class Outros {
    private String primeiroItem;
    private String segundoItem;

    public Outros( String primeiroItem, String segundoItem ) {
        this.primeiroItem = primeiroItem;
        this.segundoItem = segundoItem;
    }

    public String getPrimeiroItem() {
        return primeiroItem;
    }

    public void setPrimeiroItem( String primeiroItem ) {
        this.primeiroItem = primeiroItem;
    }

    public String getSegundoItem() {
        return segundoItem;
    }

    public void setSegundoItem( String segundoItem ) {
        this.segundoItem = segundoItem;
    }
}

Your Adapter can take the next shape:

public class MeuCustomAdapter extends BaseAdapter {
    /** Lista de objetos outros, contendo duas Strings. */
    private List<Outros> listOutros;
    /** Contexto usado para acessar recursos de string */
    private Context contexto;

    /**
     * Metodo construtor que recebe o contexto e uma lista de objetos instrumentos para popular o ListView personalizado.
     *
     * @param contexto Contexto uasdo para acessar o recurso de layout.
     * @param listOutros  Lista de objetos da representacao de cada item de lista (linha do ListView).
     */
    public MeuCustomAdapter( Context contexto, List<Outros> listOutros ) {
        this.contexto = contexto;
        this.listOutros = listOutros;
    }

    @Override
    public int getCount() {
        return listOutros.size();
    }

    @Override
    public Object getItem( int position ) {
        return listOutros.get( position );
    }

    @Override
    public long getItemId( int position ) {
        return position;
    }

    /**
     * Chamado toda vez que e necessario mostrar um item da ListView.
     *
     * @param position    A posicao do item de ListView.
     * @param convertView O elemento View que representa o item de ListView.
     * @param parent      Elemento pai do elemento view.
     */
    @Override
    public View getView( int position, View convertView, ViewGroup parent ) {
        TextView textViewTitle = new TextView( contexto );
        // Aqui é definido como texto do TextView o primeiro item do objeto Outros.
        textViewTitle.setText( listOutros.get( position ).getPrimeiroItem() );
        textViewTitle.setTextSize(18);

        // Para exibir o item você tem que retornar uma VIEW e não uma String.
        return textViewTitle;
    }
}

In Your Love you do so:

    ListView listView = findViewById( R.id.meuListView );

    Outros outros1 = new Outros( "Outros 1", "Item 1" );
    Outros outros2 = new Outros( "Outros 2", "Item 2" );
    Outros outros3 = new Outros( "Outros 3", "Item 3" );

    List<Outros> listOutros = new ArrayList<Outros>();
    listOutros.add( outros1 );
    listOutros.add( outros2 );
    listOutros.add( outros3 );

    MeuCustomAdapter meuCustomAdapter = new MeuCustomAdapter( getAplicationContext(), listOutros );
    listView.setAdapter( meuCustomAdapter );

I do not know if it will help, you have to give an extra study in Lists, Adapters, Viewholder pattern...


EDICT : And to delete a specific Listview item just do so:

To remove an item from an Arraylist you have the following options:

  1. seuArrayList.clear() - Removes all elements of the array leaving it empty;
  2. seuArrayList.remove(index) - Removes the object at the position specified in the list;
  3. seuArrayList.remove(Object) - Removes the instance of the specified object if it is contained.
  • How would I get this arrayList into another class? For example, instead of creating the items in Activity, make a class that has the items, and in Activity just make the reference. It’s like?

  • Yes. Do you happen to have any other class code for me to try to help from your code? Or don’t have the code yet?

  • I had tried, but ended up giving up and erasing, so I have to start from scratch :(

  • 1

    To create this ArrayList in another class is the same way that created in the Activity. To recover this ArrayList in his Activity is just you have an object of this your class and call some method getMeyArray() that returns your ArrayList.

  • Following the same patterns of his response, the listOutros.add( outros1 ) stays in the created class, or in the Activity?

  • From what I understand you want to do, stay in the created class.

  • I will try here, but probably only next week I will come with answers, because I will have tests this week. So, I’ll let you know anything. Thanks

  • Lucassantos: I had a time here and tested, gave straight guy, thank you again hahaha

  • @You’re welcome. rsrsrs.

  • I asked a new question, based on that answer.. things are kind of dark out there and I was wondering if you had any ideas. Thank you in advance. http://answall.com/questions/25530/como-modificar-e-salvar-o-novo-item-modificado-de-umalistview/25554#25554

Show 5 more comments

3

You can use adapter.remove() and then call the method notifyDataSetChanged() to have the changes reflected in the Listview.

Behold:

adapter.remove(adapter.getItem(index)); // Índice do item a ser deletado
adapter.notifyDataSetChanged();
  • :in my case, it would be: List.remove(List.getItem(position))?

  • Removing elements from your Adapter will only work if you use one ArrayList instead of a String[] (string array), because the number of elements needs to be variable in order for you to be able to remove an element contained in the object that your reference lug will guard.

  • @Piovezan: I edited the code, as I would change my string in the other class to an arrayList similar to that format and that of to delete?

  • @GH_ In the other class you declare for example ArrayList<String> minhaLista = new ArrayList<String>(); and adds strings to it minhaLista.add(umaString);

  • @Piovezan: I did it, but in Activity, when I call the Array, error appears: "The type of the Expression must be an array type but it resolved to Arraylist<String>". Note: I call Activity the other way Click.mylist[position]. Any hint?

  • 1

    To access the items of a ArrayList you must use minhaLista.get(position);

  • 1

    @DBX8: is updated. Please take a look at.

  • @Piovezan: I made the necessary changes, but nothing was printed on the screen.

  • @GH_ Please post all the necessary code in the question to understand what might be happening.

  • @GH_ As mentioned before, using array will not be possible to change the number of strings in the list. Make the changes that have been cited to use Arraylist. If nothing appears as you said it did, post the code containing these changes. That was the code I had requested.

  • @Piovezan: updated and found another error in setAdapter. That error of not showing the list was my mistake. I’m sorry for the waste of time. I’m looking for the error around here

  • @Piovezan: I found the bug and fixed it, but I saw that it doesn’t really show the items yet..

Show 7 more comments

Browser other questions tagged

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