Search code examples
androidandroid-recyclerviewandroid-cardviewitemtouchhelper

StartIntent from ItemTouchHelper onSwiped()


I want to open an Intent on swiping a recyclerview item. I have the below class with error in onSwiped event.

import android.support.v7.widget.helper.ItemTouchHelper.Callback;
import static android.support.v7.widget.helper.ItemTouchHelper.*;
class SwipeController extends Callback {
    private boolean swipeBack = false;

    @Override
    public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
        return makeMovementFlags(0, LEFT);
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        // Create Intent to show the Item details
        Intent intent = new Intent( getActivity(), CreateBoxActivity.class);
        intent.putExtra("parent_BoxID", parent_BoxID);
        MainActivity.this.startActivityForResult(intent, CREATE_BOX_REQUEST ); ;

    }

}

Solution

  • Try this:

    public class SwipeController extends Callback {
        private boolean swipeBack = false;
        private WeakReference<Activity> context;
    
        public SwipeController(Activity a) {
            context = new WeakReference<>(a);
        }
    
        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            return makeMovementFlags(0, LEFT);
        }
    
        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // Create Intent to show the Item details
            Intent intent = new Intent( getActivity(), CreateBoxActivity.class);
            intent.putExtra("parent_BoxID", parent_BoxID);
            Activity a = context.get();
            if (a != null && !a.isFinishing())
                  a.startActivityForResult(intent, CREATE_BOX_REQUEST );
        }
    
    }