【问题标题】:Passing a variable from one class to another in java在java中将变量从一个类传递到另一个类
【发布时间】:2012-11-28 16:27:59
【问题描述】:

我有一个 android 应用程序,我需要将一个变量(仪器)传递给它的主要活动。这似乎是一个简单的问题,但它让我感到困惑。我环顾四周,我已经注意到编写 getInstrument 方法似乎是个好主意。这是我到目前为止所做的:

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());

    }
}

单独的类(在单独的文件中):

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;
  }

}

但我认为我不能从主活动中调用 getInstrument() 方法,因为该对象仅存在于侦听器中。必须有一个非常简单的方法来解决它。我读了一些帖子,但问题似乎是该类的对象并不真正存在。感谢您提供任何见解。

【问题讨论】:

    标签: java android class variables listener


    【解决方案1】:

    你可以试试这个:

    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);  
       }
    }
    

    【讨论】:

    • 谢谢,但我想在 addListenerOnSpinner 函数之外使用 getInstrument。
    • 我实现了这个,似乎有道理。但是在调用 getInstrument (nullpoint) 时出现错误。有什么想法吗?
    • 运行时错误/AndroidRuntime(1775): java.lang.NullPointerException
    • 这可能是因为您在onItemSelected 内部初始化instrument,所以首先必须在调用getInstrument 方法之前调用它,否则instrument 将不会被初始化,因此您会得到NullPointerException
    • 我声明了双倍的监听器,这就是问题所在。现在修好了。谢谢。
    【解决方案2】:

    如果你有你的监听器的引用,你应该能够调用它的方法,例如。

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

    【讨论】:

      【解决方案3】:

      创建一个全局实例

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

      这将在 MainActivity 类中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        相关资源
        最近更新 更多