Java 在“多个”中使用一个字符串;“类”;
我对android不太在行,所以我只想问你一个问题: 我想将一些“数据”(GPS坐标)从我的位置侦听器传输到一个字符串,该字符串将在onClick函数中使用。例如:Java 在“多个”中使用一个字符串;“类”;,java,android,string,variables,global-variables,Java,Android,String,Variables,Global Variables,我对android不太在行,所以我只想问你一个问题: 我想将一些“数据”(GPS坐标)从我的位置侦听器传输到一个字符串,该字符串将在onClick函数中使用。例如: case R.id.sendButton: ParsePush push = new ParsePush(); String message = "Hey, My coordinates are - LONG:" + loc.getLongitude();; push.setCha
case R.id.sendButton:
ParsePush push = new ParsePush();
String message = "Hey, My coordinates are - LONG:" + loc.getLongitude();;
push.setChannel("test1");
push.setMessage(message);
push.sendInBackground();
break;
是的,我有位置侦听器:
class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location loc) {
mlocation.setText("");
Toast.makeText(
getBaseContext(),
"Location changed: Lat: " + loc.getLatitude() + " Lng: "
+ loc.getLongitude(), Toast.LENGTH_SHORT).show();
String longitude = "Longitude: " + loc.getLongitude();
Log.v("Long", longitude);
String latitude = "Latitude: " + loc.getLatitude();
Log.v("Lat", latitude);
等…
所以基本上,我希望能够将经度设置为某个变量(字符串),并在onClick按钮中使用该字符串
我该怎么做?任何链接都很好。谢谢 声明要在类外部使用的变量,或要通过类访问的变量,如全局变量
public static String mystring;
如果要在其他类中访问它,请通过classname.mystring访问它。
如果您想在同一个类中访问它,只需访问mystring即可。不要使用全局变量(静态)变量!!!非常非常糟糕!您应该只在一些非常有选择的编程问题中使用它们 对于这样的问题,使用get模式!下面的示例代码显示了如何使用get(和set)模式 在活动中保留一个侦听器实例
//Initialize your listener in the onCreate for example
MyLocationListener listener = ;
要获取经度或纬度,请使用:
//In the onClick
if(listener.getLongitude() != null){
//Do something with the value.
} else {
//No longitude available yet.
}
我想我找到了自己的答案。全局变量。[Java中的全局变量][1][1]:请务必小心!如果您的应用程序有一段时间处于非活动状态,Android可能会删除静态内容以释放RAM。如果您的活动再次激活,则这些字段为空!(在访问它们之前,检查它们是否为null,并相应地进行处理)使用statics进行这种设计是很糟糕的。我完全不推荐。
//In the onClick
if(listener.getLongitude() != null){
//Do something with the value.
} else {
//No longitude available yet.
}