xxx
xxx

Reputation: 1

How to get the position of a row in a listview?

Can anyone help me How can I store the value position of a row from listview when clicked? I want to use the value in onPostExecute on another class. Thanks for your time in advance. Here is my code.

 @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = LayoutInflater.from(c).inflate(R.layout.model, viewGroup, false);
        }
       ...
        final Pending s = (Pending) this.getItem(i);
       ...

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

*//here is where I want to get the position to use on my updateData()'s onPostExecute*

                final String id = 2;
                String link = "http://abcabcabc.com/abc.php?id=" + id;
                new updateData().execute(link);
            }
        });
        return view;
    }

also, how can I call it in onPostExecute to display some data?

Upvotes: 0

Views: 68

Answers (1)

Laurel Thomson
Laurel Thomson

Reputation: 106

The position of the row is the parameter i in your getView method:

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    //i is the position of the row
}

In order to use the position of the row in the onPostExecute method of an AsyncTask, you will need to pass the row position as a parameter to your "updateData" class.

However, the issue is that an AsyncTask can only take in one type of data as a parameter, and currently it is only able to accept Strings.

To get around this and be able to pass both the URL (a String) and the id/row position (an int), you could create a class (with a better name that represents what you're doing with the link):

public class DetailLink {
    private String link;
    private int id;

   //getters and setters
}

Then, in your "updateData" class, change the Params type parameter to be of type DetailLink instead of String. This will mean that your doInBackground method will accept a DetailLink as a parameter. In order to store the id so that it can be used the onPostExecute method, save it as an instance variable of the "updateData" class.

 private class UpdateDataTask extends AsyncTask<DetailLink, Void, Void> {
     private int myId;

     protected void doInBackground(DetailLink... detailLink) {
         myId = detailLink.getId();
         String url = detailLink.getLink();
         //do your task here
     }

     protected void onPostExecute() {
         //do something with the myId instance variable
     }
 }

Finally, in your getView method, you can create a new DetailLink and pass that to your execute method:

DetailLink detailLink = new DetailLink();
detailLink.setId(i);
detailLink.setLink(link);
new updateData().execute(detailLink);

Upvotes: 1

Related Questions