vendredi 26 février 2016

How to make long operations on list item click but not on UI thread?

I have a list view, in which, every item contains 3 buttons, one for saving in database, and the other two should open new fragments. I have implemented OnClickListener for which of the buttons in the getView() method of the adapter. When the user clicks the save button, I want to write item in database. Since, writing to database is considered to be long operation, and it should not be done on UI thread, I would like to ask how to do it? Should I make my own thread or can I use service or async task? Here is the code from getView:

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

    ViewHolder viewHolder;
    if(convertView==null){
        convertView=layoutInflater.inflate(R.layout.top_tracks_artists_item_layout,parent,false);

        viewHolder=new ViewHolder();
        viewHolder.trackName= (TextView) convertView.findViewById(R.id.top_tracks_item_name);

        viewHolder.trackInfo= (Button) convertView.findViewById(R.id.top_tracks_item_info);
        viewHolder.trackInfo.setTag(position);
        viewHolder.trackInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("try", "Info clicked "  +position);
            }
        });

        viewHolder.trackFavourite= (Button) convertView.findViewById(R.id.top_tracks_item_favourite);
        viewHolder.trackFavourite.setTag(position);
        viewHolder.trackFavourite.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Log.d("try", "favourites  clicked " +position);
            }
        });

        viewHolder.trackWatch= (Button) convertView.findViewById(R.id.top_tracks_item_watch);
        viewHolder.trackWatch.setTag(position);
        viewHolder.trackWatch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("try", "Watch clicked "  +position);
    //here I want to save to database

            }
        });

        convertView.setTag(viewHolder);
    }else{
        viewHolder= (ViewHolder) convertView.getTag();
    }

    viewHolder.trackName.setText((String)tracks.get(position).toString());

    return convertView;
}

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire