【问题标题】:Acessing a variable of one class from another从另一个类访问一个类的变量
【发布时间】:2016-10-10 12:05:41
【问题描述】:
public class Page3 extends Activity {
double latitude;
double longitude;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page3);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
  /* Use the LocationManager class to obtain GPS locations */
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new MyLocationListener();
    try {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
    } catch (SecurityException e) {
        e.printStackTrace();
    }
}

/* Class My Location Listener */
public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {

        double a = loc.getLatitude();
        latitude=a;

        double b = loc.getLongitude();
        longitude=b;
        String Text = "My current location is: " +
                "Latitud = " + loc.getLatitude() +
                "Longitud = " + loc.getLongitude();


        String x = getCompleteAddressString(a, b);
        TextView text = (TextView) findViewById(R.id.tv_address);
        text.setText(x);
    }

现在,我想访问另一个类中的变量纬度和经度。这是我需要访问这些变量的类。请注意:自从我得到我的当前位置(我不想把整个代码贴在这里,因为这样做没有意义) 这是我在要访问这些变量的类中编写的代码

public class Page2 extends Activity {
/**
 * ATTENTION: This was auto-generated to implement the App Indexing API.
 * See https://g.co/AppIndexing/AndroidStudio for more information.
 */
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.page2);
    Button btn = (Button) findViewById(R.id.help);
    Page3 a=new Page3();
    final double lati=a.latitude;
    double longi=a.longitude;
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendSMS("9740641023", "Help"+lati+"");
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

再次,我没有复制粘贴整个代码。这段代码本身工作正常,但现在修改它会发送消息“Help0.0”,尽管根据我的说法,纬度值应该已经更改为我当前的位置.请帮帮我。

【问题讨论】:

  • 提示:使用像 a 或 b 这样的变量名...也许可以节省 5 秒的打字时间;但是为了理解他们的意思,每个读者都需要花费几分钟和几分钟。换句话说:使用有意义的名称。 总是.
  • 据我从显示的 sn-ps 中可以看出,您正在“实例化一个新的 Page3”,但是,它的 Object.property a 还没有准备好使用,而您正在使用它。您的 MyLocationListener 没有时间更新正确的变量。要么保存值,要么使用 Singleton 来保存正确的值,或者仅在准备好时使用该值。
  • @GhostCat 下次会记住这一点。

标签: java android class variables


【解决方案1】:

您的问题基本上是 one 实例是在 in 方法中创建的:

LocationListener mLocListener = new MyLocationListener();

相反,您应该将其设为该类的字段。

而且,如果您将其设为 public static 字段,那么其他类可以使用

直接访问它
LocationListener theListner = Classname.mLocListener;

但这只是一种非常“蛮力”的做事方式。因此,您可以使用它来查看是否可以从那里取得进展;但问题是:直接从其他类访问静态字段是不好的做法;你应该避免它。

真正的教训是:这是非常基本的“java知识”。你现在应该退出“android”;并学习那些基本的 Java 东西(例如:“什么是访问其他对象中信息的合理方法”)。否则,你会撞上一堵墙!

然后,当您了解这些基础知识时;比您查看向您解释“Android 世界”如何运作的 优秀 书籍/教程。因为 Android 有时会使用非常特殊的方式来完成任务。

【讨论】:

  • 如果我让 LocationListener 本质上是静态的,那么我也必须将所有方法都更改为静态的。这就是你想说的吗?
  • 当然不是。您可以从静态和“普通”方法访问 static 字段 - 但反过来不行!并感谢我的观点:在尝试编写程序之前,您真的应该研究这些东西。否则你会从一个问题跑到下一个问题!
  • 当然我知道。我以为你想让 locationListener 类成为静态的,如果我这样做了,因为静态类只能访问静态方法,我必须将所有其他方法设为静态。还是谢谢你
  • LocationListener 是一个接口。普通类和接口没有“静态化”。你的说法根本没有任何意义!
  • *MyLocationListener 抱歉
【解决方案2】:

在 First.java 类中将该变量声明为 public static double lattitiue

现在你可以使用First.lattitude在任何类中获取这个变量的值

【讨论】:

    【解决方案3】:

    良好的数据抽象和封装允许类的客户只看到类允许客户看到的内容。您的数据成员(例如 Page3 类中的变量纬度和经度)不应被其他类直接访问。您应该有公共的 getter(访问器)和 setter(修改器)方法来限制对应该声明为私有的数据成员的“访问”。

    Java 中只能继承一个类,但可以实现任意数量的接口。因此,您不需要 Page3 类中的内部公共类 MyLocationListener。只需使用 implement 关键字并覆盖接口的方法即可。

    public class Page3 extends Activity implements LocationListener { // implement the interface instead of creating an inner class
        private double latitude; // hide your data members from the client
        private double longitude; 
    
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page3);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        /* Use the LocationManager class to obtain GPS locations */
        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    try {
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); // pass in this referring to the current class since implementing the interface LocationListener
    } catch (SecurityException e) {
        e.printStackTrace();
    }
    
    @Override
    public void onLocationChanged(Location loc) {
    
        setMyLatitude(loc.getLatitude()); // use mutator method to change value of your private data member
        setMyLongitude(loc.getLongitude()); // use mutator method to change value of your private data member
        String Text = "My current location is: " +
                "Latitud = " + loc.getLatitude() +
                "Longitud = " + loc.getLongitude();
    
    
        String x = getCompleteAddressString(a, b);
        TextView text = (TextView) findViewById(R.id.tv_address);
        text.setText(x);
    }
    
    public void setMyLatitude(double a) {
        this.latitude = a;
    }
    
    public void setMyLongitude(double b) {
         this.longitude = b;
    }
    
    public double getMyLatitude() {
         return latitude;
    }
    
    public double getMyLongitude() {
         return longitude;
    }
    }
    

    现在使用您的公共方法在第二个活动中访问您的数据成员。

    public class Page2 extends Activity {
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
     private GoogleApiClient client;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page2);
        Button btn = (Button) findViewById(R.id.help);
        Page3 a=new Page3();
        final double lati=a.getMyLatitude();
        double longi=a.getMyLongitude();
        btn.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                sendSMS("9740641023", "Help"+lati+"");
             }
         });
         // ATTENTION: This was auto-generated to implement the App Indexing API.
         // See https://g.co/AppIndexing/AndroidStudio for more information.
         client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    

    }

    这是为了良好的编程习惯。在两个活动之间进行通信的侦听器可能是您不会获得初始化的双精度值 0.0 所需要的。侦听器应在 Page2 类中实现,其数据成员设置为 Page3 类中 Page2 中的侦听器。侦听器将有一些方法来传递您想要的数据或告诉 Page2 类信息已以某种方式修改。

    public class Page2 extends Activity implements DataListener {
    .......
    @Override
    public void someMethod() {
        // do something with the data longitude and latitude as their values have changed
     }
    private GoogleApiClient client;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page2);
        Button btn = (Button) findViewById(R.id.help);
        Page3 a=new Page3();
        a.setDataListener(this); // pass listener to the other class
    /* code in Page2 */
    }
    
    public class Page3 extends Activity implements LocationListener {
    private DataListener myListener;
    /* code in Page3 */
    
    @Override
    public void onLocationChanged(Location loc) {
    
        setMyLatitude(loc.getLatitude()); // use mutator method to change value of your private data member
        setMyLongitude(loc.getLongitude()); // use mutator method to change value of your private data member
         myListener.someMethod();  // call this method to inform the other class that information has changed
    String Text = "My current location is: " +
            "Latitud = " + loc.getLatitude() +
            "Longitud = " + loc.getLongitude();
    
    
    String x = getCompleteAddressString(a, b);
    TextView text = (TextView) findViewById(R.id.tv_address);
    text.setText(x);
    }
    
    public void setDataListener(DataListener listener) {
        this.myListener = listener;
    }
    

    您也可以将经纬度直接传入Page3中的“DataListener”方法“someMethod”,甚至不需要Page3类的getter和setter以及私有数据成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2020-11-24
      • 1970-01-01
      • 2017-03-22
      • 2014-01-18
      • 2015-01-21
      相关资源
      最近更新 更多