2

So I have an onItemLongClickListener for a list view that gets a parameter 'int position' passed in. Inside, I have an alertDialogBuilder which has two buttons. I have another onclickListener for the buttons. I need to access the position from inside the second listener. Is there anyway to do this without making it a global?


public boolean onItemLongClick(AdapterView parent, View itemView, int position, long id){

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BookFace.this);
    alertDialogBuilder.setTitle("Choose an option.");
    alertDialogBuilder
    .setMessage("What would you like to do?")
    .setCancelable(true)
    .setPositiveButton("Edit", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent();
            intent.putExtra("position", position); //Can't access this variable
            intent.setClass(SomeClass.this, EditActivity.class);
            startActivity(intent);
    }

Thanks for your help.

Bibodha
  • 51
  • 1
  • 1
  • 7

2 Answers2

1

If you change position to final, then it should let you access it from within the onClick method.

Dave
  • 1,250
  • 1
  • 16
  • 32
0

In Java, you can access outer variables from an inner class declaration only if they are first declared as final. So you could add:

final int selectedPosition = position;

to the top of your method and use that value in your extra, i.e.

intent.putExtra("position", selectedPosition);
devunwired
  • 62,780
  • 12
  • 127
  • 139