Search code examples
androidsqlitelistviewonitemlongclicklistener

How can i pass item position from onItemLongClick to another class?


My question is : how can i pass item position to another class. Please see my attached code.

When i press positive button inside AlertDialog,i go to the HandleAlertDialog class , and there i delete Name by id(in database i have two variables : id and name).

I don't know how to pass id from item position to sqhelper.deleteNameByNumber(id) in HandleAlertDialog class.

Thank you for your help.

public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        AlertDialog dialog = new AlertDialog.Builder(this) 
            .setMessage("Choose one of the options")
            .setPositiveButton("Yes", new HandleAlertDialog())
            .setNeutralButton("No",new HandleAlertDialog())
            .setCancelable(false)
            .create();
        dialog.show();
        return false;
      }

    public  class  HandleAlertDialog implements DialogInterface.OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which==-1){
                sqhelper.deleteNameByNumber(**???**);
            }
        }
    }

Solution

  • You can define a id attribute in HandleAlertDialog class (I assume this is a String for my example):

    public  class  HandleAlertDialog implements DialogInterface.OnClickListener {
        private String id;
    
        public HandleAlertDialog(String id){
            this.id = id;
        }
    
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which==-1){
                sqhelper.deleteNameByNumber(id);
            }
        }
    }
    

    And then use it in your onItemLongClick:

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    
        // Retrieve id here (based on view, position ?)
        String id = "THIS IS YOUR ID";
        HandleAlertDialog handleAlertDialog = new HandleAlertDialog(id);
    
        AlertDialog dialog = new AlertDialog.Builder(this) 
            .setMessage("Choose one of the options")
            .setPositiveButton("Yes", handleAlertDialog)
            .setNeutralButton("No", handleAlertDialog)
            .setCancelable(false)
            .create();
        dialog.show();
        return false;
    }