如何从静态的静态类/方法传递数据?
我得到了静态类,它正在从服务器加载数据并将其包装到稍后进入数组并传递给普通类的对象中。我想添加参数“距离到用户”,它需要用户位置来计算。所有的项目都在不同的java类中。 从静态类的方法,它从服务器响应到对象进行排序。如何从静态的静态类/方法传递数据?
public static List<Quake> extractEarthquakes(String earthquakeJSON) {
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}
List<Quake> earthquakes = new ArrayList<>();
JSONObject jsonObj = new JSONObject(earthquakeJSON);
JSONArray features = jsonObj.getJSONArray("features");
for (int i = 0; i < features.length(); i++) {
double distance = 0;
JSONObject currentEarthquake = features.getJSONObject(i);
JSONObject properties = currentEarthquake.getJSONObject("properties");
double mag = properties.getDouble("mag");
String location = properties.getString("place");
String date = properties.getString("time");
String url = properties.getString("url");
int felt = 0;
if(!properties.isNull("felt")) {
felt = properties.getInt("felt");
}
JSONObject geometry = currentEarthquake.getJSONObject("geometry");
JSONArray coordinates = geometry.getJSONArray("coordinates");
double longitude = coordinates.getDouble(0);
double latitude = coordinates.getDouble(1);
int depth = coordinates.getInt(2);
Quake earthquake = new Quake(mag, location, date, url, felt, longitude, latitude, depth, distance);
earthquakes.add(earthquake);
}
}
return earthquakes;
}r
对象作为简单的数据保持器(只是举例一项)
public class Quake {
private double kmag;
//and others
public Quake(double mag, String location, String date, String url, int felt, double longitude, double latitude, int depth, double distance){
kmag = mag;
//and others
public double getMag() {
return kmag;
}
在MainActivity有LoaderManager这将启动加载器类工作创建。还有LocationManager获取用户的经度/纬度。到目前为止,我几乎没有想法如何做到这一点,但他们都没有工作。
- 为数组列表中的每个对象元素的设定值静态类中
- 查找位置
- 某种方式传递两个双变量为静态非静态
据我知道最后一个是不可能的。虽然在我的对象中我不能改变任何值,但它里面没有.setValue()
方法,所以我可以做的大部分事情是为kmag(用于返回的那些变量)设置新的值。
最后,我无法将我的LocationManager转移到静态类中,因为它需要询问用户权限,并且在示例中我发现所有方法都不是静态的。所以我的问题是:有什么我失踪?也许还有其他更简单的方法可以做到这一点,或者我只是在其中一个失败了?
您可以随时从类之外的任何地方调用静态方法(取决于访问修饰符)。所以,你可以调用extractEarthquakes()
法:
ItsClassName.extractEarthquakes(jsonValue);
您不能调用从静态方法非静态方法,如果方法是在同级别这样的:
public class TestClass {
public static List<Quake> extractEarthquakes(String earthquakeJSON) {
...
// This will give an error:
// Non-static method 'callExtract()` cannot be referenced from a static context
doSomething();
}
public void doSomething() {
...
}
}
但是你可以在同一个类中调用非静态方法的静态方法。
对于询问用户权限,您可以在调用静态方法之前调用它。
关键是在这里静态方法extractEarthquakes()为Quake对象提供数据。不知何故,我需要将当前设备位置(非静态方法提供)放到extractEarthquakes()中。 stackoverflow有一些私人消息系统,我可以更深入地解释吗? –
什么是“静态类”?请考虑显示相关和真实的代码。 –
欢迎来到Stack Overflow!请查看我们的[SO问题清单](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)来帮助你提出一个好问题,从而得到一个很好的答案。 –
编辑你的问题说清楚,添加一些代码。很难理解! – Xenolion