dorien
dorien

Reputation: 5407

Passing a variable from one class to another in java

I have an android app and I need to pass a variable (instrument) to its main activity. It may seem like a simple question, but it confuses me. I looked around and I already noticed that it seems like a good idea to write a getInstrument method. This is what I did so far:

public class MainActivity extends Activity{
//I need to read the instrument variable here
    public void addListenerOnSpinnerItemSelection(){

        instrumentSp = (Spinner) findViewById(R.id.instrument);
        instrumentSp.setOnItemSelectedListener(new CustomOnItemSelectedListener());

    }
}

seperate class (in seperate file):

public class CustomOnItemSelectedListener implements OnItemSelectedListener {

private int instrument;

  public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
    Toast.makeText(parent.getContext(), 
        "Please wait a minute for the instrument to be changed. ", Toast.LENGTH_SHORT).show();
        //"Item : " + parent.getItemAtPosition(pos).toString() + " selected" + pos,
        //Toast.LENGTH_SHORT).show();
     instrument = pos;
  }


  public int getInstrument(){
      return instrument;
  }

}

But I don't think I can call the getInstrument() method from the main activity, since the object only exists within the listener. There must be a really simple way around it. I read some posts, but the problem seems to be that the object of the class does not really exist. Thanks for any insights.

Upvotes: 0

Views: 1199

Answers (3)

Abubakkar
Abubakkar

Reputation: 15664

You can try this :

public class MainActivity extends Activity{
   //I need to read the instrument variable here
   CustomOnItemSelectedListener MyListener = new CustomOnItemSelectedListener();

   public void addListenerOnSpinnerItemSelection(){

     instrumentSp = (Spinner) findViewById(R.id.instrument);
     instrumentSp.setOnItemSelectedListener(MyListener);  
   }
}

Upvotes: 1

cotsios
cotsios

Reputation: 29

Create a global instance of the

CustomOnItemSelectedListener listener;
int instrument;
public void onCreate(Bundle b){
    listener = new CustomOnItemSelectedListener();
    instrument = listener.getInstrument();
}

This will be on the MainActivity class

Upvotes: 0

brabster
brabster

Reputation: 43560

If you have a reference to your listener, you should be able to call its methods, eg.

CustomOnItemSelectedListener listener = new CustomOnItemSelectedListener();
instrumentSp.setOnItemSelectedListener(listener);
....
int instrumentValue = listener.getInstrument();

Upvotes: 1

Related Questions