Alexandre Clement
Alexandre Clement

Reputation: 57

Handling a Database in setOnCLickListener(... method

In my project I want to put a Reset Button for my Database (only one entry, 4 different information I need to update to follow the user's progression in a quiz)

The problem is that I need to launch the method initDB() inside this Listener:

public class MainActivity extends Activity implements View.OnClickListener {
private Button reset = null;


@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button reset = (Button)findViewById(R.id.raz);

        DBGestion dbGestion = new DBGestion(this);
.
.
.
        reset.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v){

            dbGestion.open();
            dbGestion.initDB("Alex"); 
            dbGestion.close();
        }

    }); 

It says that I can't refer to a non-final variable (dbGestion) inside a class defined in a different method. But it doesn't work with dbGestion as a final variable..

Any idea?

Upvotes: 0

Views: 136

Answers (1)

Sam
Sam

Reputation: 86958

You have a few options to use:

  1. A field variable in MainActivity
  2. A final variable in onCreate()
  3. A field variable in the anonymous OnClickListener
  4. A local variable inside onClick()

For instance:

public class MainActivity extends Activity {
    // (1) DBGestion dbGestion;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // (1a) dbGestion = new DBGestion(this); // Instantiate field variable
        // (2) final DBGestion dbGestion = new DBGestion(this);
        reset.setOnClickListener(new OnClickListener() {
            // (3) DBGestion dbGestion = new DBGestion(MainActivity.this);
            @Override
            public void onClick(View v){
                // (4) DBGestion dbGestion = new DBGestion(MainActivity.this); or new DBGestion(v.getContext());
                dbGestion.open();
                dbGestion.initDB("Alex"); 
                dbGestion.close();
            }
        }); 

(There are more options, but they start to get eccentric.) None of these methods is inherently right or wrong, they all have their strengths and weaknesses. The choice depends on if you use dbGestion anywhere else and your personal preference.

Upvotes: 1

Related Questions